Ruby 打印注入 Do 语法
为什么下面的代码运行良好
p (1..1000).inject(0) { |sum, i|
sum + i
}
但是,下面的代码给出了错误
p (1..1000).inject(0) do |sum, i|
sum + i
end
warning: do not use Fixnums as Symbols
in `inject': 0 is not a symbol (ArgumentError)
他们应该不等价吗?
Why is it that the following code runs fine
p (1..1000).inject(0) { |sum, i|
sum + i
}
But, the following code gives an error
p (1..1000).inject(0) do |sum, i|
sum + i
end
warning: do not use Fixnums as Symbols
in `inject': 0 is not a symbol (ArgumentError)
Should they not be equivalent?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用大括号编写的块绑定到注入方法,这就是您的意图,并且它将正常工作。
但是,封装在 do/end 块中的块将绑定到 p 方法。因此,注入调用没有关联的块。在这种情况下,注入会将参数(在本例中为 0)解释为要在每个对象上调用的方法名称。由于 0 不是一个可以转换为方法调用的符号,这会产生警告。
The block written using the curly braces binds to the inject method, which is what your intention is, and it will work fine.
However, the block that is encapsulated in the do/end block, will bind to the p-method. Because of this, the inject call does not have an associated block. In this case, inject will interpret the argument, in this case 0, as a method name to call on every object. Bacuase 0 is not a symbol that can be converted into a method call, this will yield a warning.
问题出在开头的
p
上。如果你忽略这些,你会发现两者都工作正常:但这行不通:
The problem is with the
p
at the beginning. If you omit these you'll see that both work fine:But this won't work:
这看起来像是 do/end 和括号之间的绑定差异的影响:
如上面使用的括号将绑定到最后一个链接的函数,而 do/end 将绑定到第一个函数。
我认为这是一种奇怪的说法,但基本上第一个实例是将块传递给函数“inject”,而第二个实例实际上试图将块传递给第一个方法“p”。
This looks like a effect of the difference in binding between do/end and brackets:
brackets, used as you are above, will bind to the last function chained while do/end will bind to the first.
I think thats sort of a odd way to say it, but basically the first instance is passing the block to the function 'inject', while the second is actually trying to pass the block to the first method 'p'.