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

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

问题描述

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

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

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

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