do..end对Ruby的大括号 [英] do..end vs curly braces for blocks in Ruby
问题描述
我有一个同事正在积极地试图说服我,我不应该使用do..end,而是使用花括号来定义Ruby中的多行块。
I have a coworker who is actively trying to convince me that I should not use do..end and instead use curly braces for defining multiline blocks in Ruby.
我坚定地在营地只使用大括号短的一线和do..end为一切。但我想我会联系更大的社区得到一些解决方案。
I'm firmly in the camp of only using curly braces for short one-liners and do..end for everything else. But I thought I would reach out to the greater community to get some resolution.
那是什么,为什么呢? (一些代码的示例)
So which is it, and why? (Example of some shoulda code)
context do
setup { do_some_setup() }
should "do somthing" do
# some more code...
end
end
或
context {
setup { do_some_setup() }
should("do somthing") {
# some more code...
}
}
推荐答案
puts [1,2,3].map{ |k| k+1 }
2
3
4
=> nil
puts [1,2,3].map do |k| k+1; end
#<Enumerator:0x0000010a06d140>
=> nil
这意味着{}具有比do..end更高的优先级,
This means that {} has a higher precedence than do..end, so keep that in mind when deciding what you want to use.
PS:在开发您的偏好设置时,还要记住一个例子。
P.S: One more example to keep in mind while you develop your preferences.
以下代码:
task :rake => pre_rake_task do
something
end
真的意味着:
task(:rake => pre_rake_task){ something }
此代码:
task :rake => pre_rake_task {
something
}
真的意味着:
task :rake => (pre_rake_task { something })
为了获得所需的实际定义,使用大括号必须执行:
So to get the actual definition that you want, with curly braces, you must do:
task(:rake => pre_rake_task) {
something
}
也许使用大括号是参数是你想做的反正,但如果你不这样做最好使用在这些情况下,避免这种混乱。
Maybe using braces for parameters is something you want to do anyways, but if you don't it's probably best to use do..end in these cases to avoid this confusion.
这篇关于do..end对Ruby的大括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!