Ruby做/结束vs括号 [英] Ruby do/end vs braces
本文介绍了Ruby做/结束vs括号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
根据我使用花括号还是使用do/end,为什么此地图表达式会产生不同的结果?
Why does this map expression produce different results depending on whether I use braces or do/end?
a = [1,2,3,4,5]
p a.map { |n|
n*2
}
#=> [2,4,6,8,10]
p a.map do |n|
n*2
end
#=> [1,2,3,4,5]
推荐答案
这是因为第二行被解释为:
That's because the second line is interpreted as:
p(a.map) do ... end
代替:
p(a.map do ... end)
在这种情况下,语法是模棱两可的,do
似乎没有像{
那样牢固地绑定.
The grammar is ambiguous in this case and do
doesn't seem to bind as strongly as {
.
这篇关于Ruby做/结束vs括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文