2

好的,所以我试图解决这个难题中的第 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
4

2 回答 2

1

define_singleton_method如果它是您想要的方法,则将块传递给:

def can(*actions, &block)
  actions.each do |action|
    if block_given?
      define_singleton_method(action, block)
    else
      define_singleton_method(action) { "#{name} #{MSGS[action]}" }
    end
  end
end

这会输出您所期望的。

(Delta 将 stimpy 首先证明cry不在其他实例上,并且cry每个实例都调用。)

Stimpy is dancing
Stimpy can't poo
Stimpy can't laugh
Stimpy cried AHHHH

Lassie is dancing
Lassie is a smelly doggy!
Lassie finds this hilarious!
Lassie can't cry

Fido can't dance
Fido is just wayyyy too smelly.
Fido can't laugh
Fido can't cry
于 2012-12-29T02:38:31.120 回答
1

1:你创建了一个丑陋的方法:

self.instance_eval {} == define_singleton_method(callback, &block)

你应该使用一个,但不能同时使用!

2:因为使用时范围发生了变化

self.instance_eval do 
   #coding
end

你不能使用变量:name,所以只使用define_singleton_method!

对不起,我的英语很差!

于 2012-12-29T03:19:31.350 回答