Ruby do/end 与大括号
为什么这个映射表达式会根据我使用大括号还是 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]
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]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是因为第二行被解释为:
而不是:
在这种情况下,语法是模棱两可的,而
do
似乎并不像{
那样强烈。That's because the second line is interpreted as:
instead of:
The grammar is ambiguous in this case and
do
doesn't seem to bind as strongly as{
.这与
{
字符和do
关键字的关联性差异有关。在第一种情况下,块被解释为
map
函数的块参数。 map 函数的结果是p
函数的参数。在第二种情况下,该块被解释为
p
函数的块参数,而a.map
被解释为p< /代码> 函数。由于
a.map
的计算结果为a
,因此会打印原始数组。在这种情况下,该块实际上被忽略。That has to do with the difference in associativity of the
{
character and thedo
keyword.In the first case, the block is interpreted as a block argument to the
map
function. The result of the map function is the argument to thep
function.In the second case, the block is interpreted as a block argument to the
p
function, while thea.map
is interpreted as the first argument to thep
function. Sincea.map
evaluates toa
, this prints the original array. The block is effectively ignored in this case.使用 do/end 语法,您可以将块作为第二个参数传递给 p,而不是传递给映射。您会得到相同的结果:
该块被
p
忽略,因为它不会在inspect
上产生任何内容。With the
do/end
syntax you are passing the block top
as a second argument, rather than to the map. You get the same result with:The block is ignored by
p
as it does not produce anything oninspect
.