Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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
- class Hero
- def initialize(mass)
- @mass = mass
- end
- def <=>(hero)
- mass <=> hero.mass
- end
- protected #I put this as protected since you did, but I would likely leave it public
- attr_reader :mass
- end
- class Finn < Hero
- def initialize(mass, sword_length)
- @mass = mass
- @sword_length = sword_length
- end
- def <=>(finn)
- if finn.respond_to? :sword_length
- (mass + sword_length) <=> (finn.mass + finn.sword_length)
- else
- super(finn)
- end
- end
- protected
- attr_reader :sword_length
- end
- class Jake < Hero
- def initialize(mass, fist_length)
- @mass = mass
- @fist_length = fist_length
- end
- #edited
- def <=>(jake)
- if jake.respond_to? :fist_length
- (mass + fist_length) <=> (jake.mass + jake.fist_length)
- else
- super(jake)
- end
- end
- protected
- attr_reader :fist_length
- end
- class Hero
- attr_reader :mass
- # more info in attr_reader and attr_accessor is here http://stackoverflow.com/questions/5046831/why-use-rubys-attr-accessor-attr-reader-and-attr-writer
- def initialize mass
- @mass = mass
- end
- def <=> hero
- mass <=> hero.mass
- end
- end
- class Finn < Hero
- attr_reader :sword_length
- def initialize mass, sword_length
- @sword_length = sword_length
- super(mass)
- end
- def <=> finn
- if finn.class == self.class
- (@mass+@sword_length) <=> (finn.mass+finn.sword_length)
- else
- super(finn)
- end
- end
- end
- class Jake < Hero
- attr_reader :fist_length
- def initialize mass, fist_length
- @fist_length = fist_length
- super(mass)
- end
- def <=> jake
- #alternate dense way to do it
- jake.class == self.class ? ((@mass+@fist_length) <=> (jake.mass+jake.fist_length)) : super(jake)
- end
- end
- hero1 = Finn.new(10, 80)
- hero4 = Jake.new(50, 18)
- puts " error? "+(hero1<=>hero4).to_s
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement