好了,所以我試圖solve step 2 in this puzzle,我有麻煩了。我的問題是在試圖訪問一個實例變量(@name)
甚至呼籲類(name getter)
方法,紅寶石告訴我不確定局部變量。對我來說,這似乎是一個範圍問題。當一個動作名稱和一個塊作爲參數給出時,問題就出現了。單身人士正在成功添加到實例變量,我相信但調用它,紅寶石告訴我,「名稱」是一個未定義的局部變量。有任何想法嗎?任何想法如何更有效地仿效功能的其他方式?添加單方法和訪問實例變量 - 未定義
這裏是我的Dog.rb類:
class Dog
MSGS = {:dance => 'is dancing', :poo => 'is a smelly doggy!', :laugh => 'finds this hilarious!'}
attr_accessor :name
def initialize(name)
@name = name
end
def can(*actions)
actions.each do |action|
self.instance_eval do
if block_given?
define_singleton_method action do
yield
end
else
define_singleton_method(action) do
name + ' ' + MSGS[action]
end
end
end
end
end
def method_missing(method_name,*args)
name + " can't " + method_name.to_s
end
end
這裏是Dog_Game.rb從拼圖:
require './dog'
lassie, fido, stimpy = %w[Lassie Fido Stimpy].collect{|name| Dog.new(name)}
lassie.can :dance, :poo, :laugh
fido.can(:poo){"#{name} is just wayyyy too smelly."} #name here is the source of the problem
stimpy.can :dance
stimpy.can(:cry){"#{name} cried AHHHH"}
p lassie.dance
p lassie.poo
p lassie.laugh
puts
p fido.dance
p fido.poo
p fido.laugh
puts
p stimpy.dance
p stimpy.poo
p stimpy.laugh
p stimpy.cry
謝謝!現在按預期工作 – foklepoint