저는 루비가 처음입니다. 나는 Java와 C++에 익숙하다. 내가 이해하려고 노력한 것은 언어의 다형성을 사용하는 방법입니다. 또한 상속의 규칙. 간단한 작업 코드를 만들었지 만 이해가 안됩니다. 다른 방법이 있습니까? 루비에는 항상 다른 방법이 있습니다.Ruby, 다형성, 상속 및 self.class
설명 : 어린이와 같은 자녀가 동일한 수업에 속하는 경우 비교합니다. 그렇지 않으면 부모와 같이 비교합니다.
시간을 낭비하면 죄송합니다. 인터넷 검색이 도움이되지 않아 좋은 쿼리를 작성할 수 없습니다.
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
(@[email protected]_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
(@[email protected]_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
감사합니다. 이제 나는 모든 정보를 어디서 발굴해야하는지 알고 있습니다! =) – Jamato
나는 fist_length와 : sword_length를 심볼로 편집했다. 이 편집을 승인하지 않으셨습니까? – Jamato
Jamato에게 감사드립니다. 미안합니다. 나는 오늘 아침에 대답했을 때 나는 약간 졸 았고 원래의 코드에서 복사/붙여 넣기 및 다시 포맷하기와 결합하면 그 실수를 피할 수있었습니다. 편집 해 주셔서 감사합니다. –