do..end 与 Ruby 中块的花括号 [英] do..end vs curly braces for blocks in Ruby

查看:21
本文介绍了do..end 与 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.

我坚定地站在只使用花括号作为短单行代码的阵营中,并且做..结束其他所有事情.但我想我会联系更大的社区来解决问题.

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...
  }
}

就我个人而言,仅看上面的内容就回答了我的问题,但我想向更大的社区开放.

Personally, just looking at the above answers the question for me, but I wanted to open this up to the greater community.

推荐答案

一般约定是多行块使用 do..end ,单行块使用花括号,但两者也有区别可以用这个例子来说明:

The general convention is to use do..end for multi-line blocks and curly braces for single line blocks, but there is also a difference between the two that can be illustrated with this example:

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.

P.S:在您制定偏好时要记住的另一个例子.

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
}

也许无论如何您都想为参数使用大括号,但如果不这样做,最好在这些情况下使用 do..end 以避免这种混淆.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆