好的,所以我试图解决这个难题中的第 2 步,但遇到了麻烦。我的问题是在尝试访问实例变量(@name)
甚至调用类上的方法时(name getter)
,ruby 告诉我未定义的局部变量。对我来说,这似乎是一个范围问题。当一个动作名称和一个块作为参数给出时,问题就出现了。我相信一个单例已成功添加到实例变量中,但调用它时,ruby 告诉我“名称”是一个未定义的局部变量。有任何想法吗?知道如何以其他方式更有效地模拟该功能吗?
这是我的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