下面的 ruby 语法中的“&”是什么意思?
在下面的 ruby 示例中,&
代表什么?是沿着循环中的+=
线吗?
payments.sum(&:price)
谢谢,
里奇
In the following ruby example, what does the &
represent? Is it along the line of +=
in a loop?
payments.sum(&:price)
Thanks,
Rich
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
&:price 是“对集合的每个成员使用 #price 方法”的简写。
一元“&”,当作为参数传递到方法中时,告诉 Ruby“将其转换为 Proc”。符号上的 #to_proc 方法将将该符号 #send 到接收对象,该对象通过该名称调用相应的方法。
&:price is shorthand for "use the #price method on every member of the collection".
Unary "&", when passed as an argument into a method tells Ruby "take this and turn it into a Proc". The #to_proc method on a symbol will #send that symbol to the receiving object, which invokes the corresponding method by that name.
不,它与
+=
无关。一元&
运算符在方法调用中使用时,会将给定的 Proc 对象转换为块。如果操作数不是 Proc(在本例中它是符号),则首先对其调用to_proc
,然后将生成的 Proc 对象转换为块。No, it has nothing to do with
+=
. The unary&
operator, when used in a method call, turns the given Proc object into a block. If the operand is not a Proc (as in this case where it is a symbol), firstto_proc
is called on it and then the resulting Proc object is turned into a block.“如果方法的最后一个参数前面有一个 & 符号,Ruby 会认为它是一个 Proc 对象。它将它从参数列表中删除,将 Proc 对象转换为一个块,并将其与该方法关联起来。”
来自 Ruby 编程:实用程序员指南
阅读更多相关内容 本文。
"If the last argument to a method is preceded by an ampersand, Ruby assumes that it is a Proc object. It removes it from the parameter list, converts the Proc object into a block, and associates it with the method."
From Programming Ruby: The Pragmatic Programmers' Guide
Read more about it in this article.
我算不上 Ruby 专家,但我记得,它的含义与 C/C++ 中的含义大致相同,在 C/C++ 中它是地址运算符。换句话说,方法
price
本身作为参数传递给sum
,而不是调用price
,并将结果传递给sum
I'm hardly a Ruby expert, but as I recall, it means much the same as it would in C/C++, where it is the address-of operator. In other words, the method
price
itself is passed as an argument tosum
, instead ofprice
being called, and the result being passed tosum