Ruby 块和无括号的参数
我提取了简单的例子:
require 'pp'
x = 1..3
pp x.map do |i| {:value => i, :double => (i*2)} end
pp x.map { |i| {:value => i, :double => (i*2)} }
pp(x.map do |i| {:value => i, :double => (i*2)} end)
pp(x.map { |i| {:value => i, :double => (i*2)} })
我想知道为什么第一个 pp 会产生:
[1, 2, 3]
虽然所有订单都给出:
[{:value=>1, :double=>2}, {:value=>2, :double=>4}, {:value=>3, :double=>6}]
我认为它与运算符优先级有关。 我在哪里可以找到好的解释?
I extracted simple example:
require 'pp'
x = 1..3
pp x.map do |i| {:value => i, :double => (i*2)} end
pp x.map { |i| {:value => i, :double => (i*2)} }
pp(x.map do |i| {:value => i, :double => (i*2)} end)
pp(x.map { |i| {:value => i, :double => (i*2)} })
I am wondering why first pp produces:
[1, 2, 3]
While all the oders are giving:
[{:value=>1, :double=>2}, {:value=>2, :double=>4}, {:value=>3, :double=>6}]
I assume it has something to do with operator precedence. Where can I find good explanation?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是因为您正在调用
并向 pp 传递一个块(它会忽略它),
如 Programming Ruby 中所述 书
,因此,实际上,大括号绑定到最接近它们的函数调用 (x.map),而 do 绑定到最远的函数调用 (pp)。 这有点简单,但应该可以解释这种情况
It's because you're calling
and passing a block to pp (which ignores it)
As explained in the Programming Ruby book
So, effectively, braces tie to the function call closest to them (x.map) whereas do binds to the furthest away (pp). That's a bit simplistic but it should explain this situation