块定义 - 大括号和 do-end 之间的区别? [英] Block definition - difference between braces and do-end?

查看:31
本文介绍了块定义 - 大括号和 do-end 之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以解释为什么以下代码会因错误而中止

can anybody explain why the following code aborts with an error

irb(main):186:0> print ((1..10).collect do |x| x**2 end)
SyntaxError: (irb):186: syntax error, unexpected keyword_do_block,
expecting ')'
print ((1..10).collect do |x| x**2 end)
                         ^
(irb):186: syntax error, unexpected keyword_end, expecting $end
print ((1..10).collect do |x| x**2 end)
                                      ^
        from /usr/bin/irb:12:in `<main>'

而以下具有相同功能的代码是否按预期工作?

whereas following code with the same functionality works as expected ?

irb(main):187:0> print ((1..10).collect { |x| x**2 })
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]=> nil

我确实相信花括号{}"可以在块中任意替换do end"定义.

I did believed curly-braces "{ }" can substitute "do end" arbitrarily at block definition.

我知道我可以通过省略打印之间的空格来修复"第一个调用方法和第一个括号,但我对解释感兴趣为什么它的行为不同.

I know I can "fix" the first call by omitting a space between print method and the first parenthesis, but I'm interested in an explanation why it behaves different.

推荐答案

区别在于优先级:

# Equivalent to puts( (1..10).map { |i| i*2 } )
> puts (1..10).map { |i| i*2 }
2
4
6
8
10
12
14
16
18
20
 => nil 

# Equivalent to puts( (1..10).map ) { |i| i*2 }
> puts (1..10).map do |i| i*2 end
#<Enumerator:0x928f24>
 => nil 

在第一种情况下,块被传递给map,一切正常.在第二种情况下,块被传递给 puts,它不会对它做任何事情.map 不接收块,只返回一个枚举器.

In the first case, the block is passed to map, and everything works properly. In the second case, the block is passed to puts, which doesn't do anything with it. map doesn't receive a block and just returns an enumerator.

至于语法错误,如果你去掉print(之间的空格,一切正常;)

As for the syntax error, if you remove the space between print and ( everything works ;)

区别在于 ruby​​ 是将括号视为方法参数分隔符,还是将其视为通用语句分组.我不确定那里的确切区别,但它微妙而烦人

The difference is whether ruby is treating your parentheses as method argument delimiters, or whether it's a generic statement grouping. I'm not sure of the exact difference there but it's subtle and annoying

这篇关于块定义 - 大括号和 do-end 之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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