使用 do 块与大括号 {} [英] Using do block vs braces {}

查看:38
本文介绍了使用 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 brace syntax would allow you to place the block on one line

my_array.each { |item| puts item }

但除此之外,还有什么令人信服的理由来使用一种语法而不是另一种吗?

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

推荐答案

Ruby 食谱 说括号语法的优先级高于 do..end

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

请记住括号语法具有更高的优先级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天全站免登陆