Possible Duplicate:
What’s this &block in Ruby? And how does it get passes in a method here?
我不明白 &block
部分,它是做什么的?
这是一个例子:
def method_missing(method_name, *args, &block)
@messages << method_name
@object.send method_name, *args, &block
end
block
让您有机会声明一个回调以传递给一个方法。
&
是这里的关键 - 就像 @pst 提到的,它将 block “提升”为 Proc,并将 Proc 绑定(bind)到具有给定名称的变量。
与 &
def time(&block)
puts block
end
time
# => nil
time { foo }
# => #<Proc:0x00029bbc>
没有 &
def time(block)
puts block
end
time { foo }
# => ArgumentError: wrong number of arguments (0 for 1)
# Because & isn't included, the method instead expected an arguement,
# but as a block isn't a arguement an error is returned.