2016-12-01 1 views
1

Human 클래스의 ogre 객체의 swing 속성에 액세스하려고합니다. 그러나 내가 얻는 것은 다음과 같습니다. NameError: undefined local variable or method ogre for **<Human:0x007fdb452fb4f8 @encounters=3, @saw_ogre=true> 아마도 가장 쉬운 해결책 일 수 있으며, 내 두뇌는 오늘 아침에 작동하지 않습니다. 나는 minitest로 테스트를하고있다. 테스트와 클래스는 다음과 같습니다 : 쉬운 수정 encounters에 인수로 오우거 개체를 전달하는 것입니다attr_accessor - 다른 클래스의 객체 속성에 액세스

ogre_test.rb
def test_it_swings_the_club_when_the_human_notices_it 
    ogre = Ogre.new('Brak') 
    human = Human.new 
    ogre.encounter(human) 
    assert_equal 0, ogre.swings 
    refute human.notices_ogre? 

    ogre.encounter(human) 
    ogre.encounter(human) 

    assert_equal 1, ogre.swings 
    assert human.notices_ogre? 
end 

class Ogre 
    attr_accessor :swings 
    def initialize(name, home='Swamp') 
    @name = name 
    @home = home 
    @encounters = 0 
    @swings = 0 
    end 

    def name 
    @name 
    end 

    def home 
    @home 
    end 

    def encounter(human) 
    human.encounters 
    end 

    def encounter_counter 
    @encounters 
    end 

    def swing_at(human) 
    @swings += 1 
    end 

    def swings 
    @swings 
    end 
end 


class Human 

    def initialize(encounters=0) 
    @encounters = encounters 
    @saw_ogre = false 
    end 

    def name 
    "Jane" 
    end 

    def encounters 
    @encounters += 1 
    if @encounters % 3 == 0 and @encounters != 0 
     @saw_ogre = true 
    else 
     @saw_ogre = false 
    end 
    if @saw_ogre == true 
     ogre.swings += 1 # <----issue 
    end 
    end 

    def encounter_counter 
    @encounters 
    end 

    def notices_ogre? 
    @saw_ogre 
    end 
end 

답변

0

ogre.rb - encounters ISN 가정 인수없이 다른 곳에서는 사용되지 않습니다.

class Ogre 
    ... 

    def encounter(human) 
    human.encounters(self) 
    end 

    ...  
end 


class Human 
    ... 

    def encounters(ogre) 
    @encounters += 1 
    if @encounters % 3 == 0 and @encounters != 0 
     @saw_ogre = true 
    else 
     @saw_ogre = false 
    end 
    if @saw_ogre == true 
     ogre.swings += 1 # <----issue 
    end 
    end 

    ... 
end 
+0

고맙습니다! 그래서 저는 논쟁을 지나치지 않았기 때문에 그것을 사용할 수 없었습니다. 이론적으로 attr_accessor를 어떻게 사용하려고했는지의 기초가 되었습니까? –

+0

그것은 그것을하는 '방법'입니다. 여러 가지가 있지만 이것은 나에게 잘 보입니다. – Biketire

+0

@ Prodigy_Internet :이 대답에서 설명한 것처럼 간단한 범위 문제가있었습니다. 'attr_accessor'는 사진에 전혀 들어가지 않습니다. 그러나, 당신이 묻기 때문에 : 아니오, 이것은 절대적으로 끔찍합니다. 당신은 임의의 숫자에 그것을 할당함으로써 누군가가 임의적으로'스윙'의 가치를 바꾸도록 허용하고 있습니다. 이 정보로 얻고 자하는 것이 무엇인지 명확하게 알 수는 없지만 여기에는 두 가지 아이디어가 있습니다. 오우거가 피곤한지를 확인하기 위해 그것을 사용한다면, 나는 우스꽝스럽게 높은 가치로 설정함으로써 어떤 싸움에서 이기기 만하면됩니다. 당신이 오우거가 얼마나 자주 나를 때렸는지 계산하기 위해 그것을 사용한다면, 나는 이길 수 있습니다 ... –

관련 문제