本文介绍了Ruby 块和无括号的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我提取了一个简单的例子:
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)} })
我想知道为什么第一个 pp 会产生:
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?
推荐答案
因为你在打电话
pp x.map
并将块传递给 pp(忽略它)
and passing a block to pp (which ignores it)
如编程 Ruby 一书中所述
大括号具有高优先级;do 的优先级较低
因此,有效地,大括号绑定到离它们最近的函数调用(x.map),而 do 绑定到最远的函数调用(pp).这有点简单,但它应该可以解释这种情况
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
这篇关于Ruby 块和无括号的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!