ruby - 在 ruby​​ 中, "&block"是做什么的?

标签 ruby

<分区>

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.

关于ruby - 在 ruby​​ 中, "&block"是做什么的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13655014/

相关文章:

ruby-on-rails - Ruby on Rails - 如何委托(delegate)给多态关联?

ruby - 有没有办法从 Jekyll 的 [site.time] 属性轻松解析年份?

ruby-on-rails - Ruby on Rails 中属性包装器的设计模式

ruby - DataMapper 按关联计数过滤记录

ruby - 标题大写

ruby - 为什么我的 ruby​​ 字符串变成了一个数组?

ruby-on-rails - 如何计算自 Ruby 中的给定日期以来经过了多少年?

mysql - 似乎无法找到 mysql 数据库

ruby - Sinatra 成功案例

ruby - 使用 Ruby Enterprise v1.8.7 安装 ruby​​-debug/ruby-debug-base 时出错