kim3er
kim3er

Reputation: 6476

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(&:price)

Thanks,

Rich

Upvotes: 4

Views: 330

Answers (4)

Scott Arrington
Scott Arrington

Reputation: 12523

"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.

Upvotes: 1

sepp2k
sepp2k

Reputation: 370455

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.

Upvotes: 1

mattt
mattt

Reputation: 19544

&: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.

Upvotes: 3

Stack Overflow is garbage
Stack Overflow is garbage

Reputation: 248289

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

Upvotes: -1

Related Questions