【问题标题】:Basic ruby question: the { } vs do/end construct for blocks [duplicate]基本的 ruby​​ 问题:块的 { } vs do/end 构造[重复]
【发布时间】:2010-02-12 07:49:34
【问题描述】:

可能的重复:
Using do block vs brackets {}
What is the difference or value of these block coding styles in Ruby?

为什么会这样:

test = [1, 1, 1].collect do |te|
    te + 10
end
puts test

有效,但无效:

puts test = [1, 1, 1].collect do |te|
    te + 10
end

但这是可行的:

puts test = [1, 1, 1].collect { |te|
    te + 10
}

对于我不知道的块,do/end 构造和 { } 构造之间有区别吗?

【问题讨论】:

标签: ruby programming-languages syntax


【解决方案1】:

在“不工作”的情况下,该块实际上附加到puts 调用,而不是collect 调用。 {}do 绑定得更紧密。

下面的显式括号展示了 Ruby 解释上述语句的方式的不同:

puts(test = [1, 1, 1].collect) do |te|
    te + 10
end

puts test = ([1, 1, 1].collect {|te|
    te + 10
})

【讨论】:

  • 您是否可以遵循一般规则来预测这种行为?
  • 好吧,可以肯定的是,检查优先规则 (ruby-doc.org/docs/ProgrammingRuby/language.html#table_18.4)。但根据经验,我总是将 do...end 视为代码块,将 {} 视为函数;另外,切勿将 do...end 放在 {} 中。
猜你喜欢
  • 1970-01-01
  • 2011-07-27
  • 1970-01-01
  • 2020-10-21
  • 1970-01-01
  • 2021-09-22
  • 1970-01-01
  • 2023-03-25
  • 1970-01-01
相关资源
最近更新 更多