1
Humanクラスのogreオブジェクトのswing属性にアクセスしたいとします。しかし、私が得ているのは次のとおりです。 NameError: undefined local variable or method ogre for **<Human:0x007fdb452fb4f8 @encounters=3, @saw_ogre=true>
ほとんどの場合、単純な解決策であり、私の脳は今朝起きていません。私はminitestでテストを実行しています。試験クラスは以下の通りである:簡単な修正はencounters
の引数として鬼オブジェクトを渡すことであろうattr_accessor - 別のクラスのオブジェクト属性にアクセスする
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
THANKS!それで、私が議論を通過していなかったので、それは使用できませんでした。私はattr_accessorを理論的に正しいものにしようとしていたのですか? –
それはそれを行う方法です。複数あるが、これは私にはうまく見える。 – Biketire
@ Prodigy_Internet:この回答では、簡単なスコープの問題がありました。 'attr_accessor'は画像にまったく入っていません。しかし、あなたが尋ねているので:いいえ、これは絶対にひどいです。あなたは任意の数値に任意の数を割り当てることによって、誰でも 'スイング 'の値を任意に変更できるようにしています。あなたがその情報で達成したいことははっきりしていませんが、ここでは2つのアイデアがあります。鬼が疲れているかどうかを確認するために使用している場合は、まず、何かを無計画に高い価値に設定することによって、あなたが鬼が私に当たった回数を数えるためにそれを使用しているなら、私は勝つことができます... –