0
我想從頭開始在Ruby中實現觀察者模式,但是在編程時,我無法理解的錯誤阻止了我。爲什麼我不能將對象推入實例數組?
我創建了一些對象添加到一個實例陣列的方法,但是當我把這種方法,解釋返回我一個錯誤,指出:
未定義的方法
push' for nil:NilClass Did you mean? puts (repl):15:in
的addObserver」 (REPL): 36:in''
我已經定義了數組,所以你知道我爲什麼會收到這個錯誤嗎?
(當我打電話我收到此錯誤:matchOne.addObserver(playerOne))
下面是完整的代碼:
class Match
attr_accessor :observers, :result
@observers = Array.new
@result = 0
def notifyAll
@observers.each do |observer|
observer.update(self)
end
end
def addObserver(observer)
@observers.push(observer)
end
def increaseResult
@result += 1
notifyAll
end
end
class Player
def update(match)
puts "The result is #{match.result}"
end
end
playerOne = Player.new
matchOne = Match.new
matchOne.addObserver(playerOne)
我感謝你在前進的幫助。
是否有必要,這兩個變量的方法中實例化? –
該代碼已執行,但與其他方法中的代碼不在同一範圍內。所以如果你想在'addObserver'等中訪問這些變量,你應該把它放在初始化方法中。 – Ursus
謝謝,現在我明白了:) –