使用do块和括号{} [英] Using do block vs brackets {}

查看:112
本文介绍了使用do块和括号{}的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

新手上路,戴上新手套。

New to ruby, put on your newbie gloves.

以下两个片段之间有什么区别(模糊或实用)?

Is there any difference (obscure or practical) between the following two snippets?

my_array = [:uno, :dos, :tres]
my_array.each { |item| 
    puts item
}

my_array = [:uno, :dos, :tres]
my_array.each do |item| 
    puts item
end

我意识到括号语法会允许你放置一行上的块

I realize the bracket syntax would allow you to place the block on one line

my_array.each { |item| puts item }

但是除此之外还有什么令人信服的理由使用一种语法? / p>

but outside of that are there any compelling reasons to use one syntax over the other?

推荐答案

Ruby cookbook 说括号语法的优先顺序高于 do..end

Ruby cookbook says bracket syntax has higher precedence order than do..end


考虑以下
两个代码片段:

Keep in mind that the bracket syntax has a higher precedence than the do..end syntax. Consider the following two snippets of code:



1.upto 3 do |x|
  puts x
end

1.upto 3 { |x| puts x }
# SyntaxError: compile error

第二个示例仅在使用括号时起作用, 1.upto(3){| x | puts x}

Second example only works when parentheses is used, 1.upto(3) { |x| puts x }

这篇关于使用do块和括号{}的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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