What does the `&` mean in the following ruby syntax?
In the following ruby example, what does the &
represent? Is it along the line of +=
in a loop?
payments.sum(&a开发者_JAVA技巧mp;:price)
Thanks,
Rich
&: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.
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), first to_proc
is called on it and then the resulting Proc object is turned into a block.
"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.
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 to sum
, instead of price
being called, and the result being passed to sum
精彩评论