I'm quite new to ruby. I'm used to Java and C++ though. What I was trying to understand is how to use polymorphism of the language. And also rules of inheritance. I've made a simple working code but I can't understand how good is it. Are there any other ways? There are always other ways in ruby as far as I know.
What it does: compares children like children if they belong to the same class. Otherwise compares them like their parent.
Sorry if I've wasted your time. Googling didn't help, I can't make a good query.
class Hero
public
#redefine comparison like this just for the sake of having it use protected method
def <=> hero
@mass <=> hero.get_mass
end
def initialize mass
@mass = mass
end
protected
#this protected method is used for inheritance testing purposes
def get_mass
@mass
end
end
class Finn < Hero
def initialize mass, sword_length
@mass = mass
@sword_length = sword_length
end
# THIS! Am I doing this right?
def <=> finn
if finn.class == self.class
(@mass+@sword_length) <=> (finn.get_mass+finn.get_sword_length)
else
super(finn)
end
end
# probably not...
protected
def get_sword_length
@sword_length
end
end
class Jake < Hero
def initialize mass, fist_length
@mass = mass
@fist_length = fist_length
end
def <=> jake
if jake.class == self.class
(@mass+@fist_length) <=> (jake.get_mass+jake.get_fist_length)
else
super(jake)
end
end
protected
def get_fist_length
@fist_length
end
end
hero1 = Finn.new(10, 80)
hero4 = Jake.new(50, 18)
puts " error? "+(hero1<=>hero4).to_s