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

查看:99
本文介绍了使用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 }

,但是除此之外,是否有令人信服的理由使用一种语法而不是另一种? / p>

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 |放x}

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

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

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