我目前正在从this metaprogramming tutorial 做第二周任务1,并有一些与define_method使用它的发送块的问题。程序根本看不到块,当我调用block_given时返回false?即使我提供了一个块。define_method没有收到块作为参数ruby
下面是发送数据块文件:
require_relative 'dog'
lassie, fido, stimpy = %w[Lassie Fido Stimpy].collect{|name| Dog.new(name)}
lassie.can :dance, :poo, :laugh
fido.can :poo
stimpy.can :dance
stimpy.can(:cry){"#{name} cried AHHHH"} # the block that I can't receive
puts lassie.name
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 # method call
和接收文件:
如果Dog = Class.new do
MESSAGES = { dance: "is dancing", poo: "is a smelly doggy!", laugh: "finds this hilarious" }
define_method :initialize do |name|
instance_variable_set(:@name, name)
end
define_method :name do
instance_variable_get :@name
end
define_method :can do |*args, &block|
puts block_given? # false
if block_given?
define_method args.to_sym do
yield
end
else
args.each do |ability|
self.class.instance_eval do
define_method "#{ability}".to_sym do
@name + " " + MESSAGES[ability]
end
end
end
end
end
define_method :method_missing do |arg|
puts "#{@name} doesn't understand #{arg}"
end
end
如果块被给出,为什么你要定义一个方法?如果这就是你应该做的事情,那么在splatted数组上调用'to_sym'的结果是什么? –
@DaveNewton我甚至无法收到该块,所以我无法编辑程序的这一部分。我发送唯一的参数时通过一个块,它的方法名称 – poctek
这与Rails无关,所以你应该删除Rails标签。 –