What does the `&` mean in the following ruby syntax?

前端 未结 4 604

In the following ruby example, what does the & represent? Is it along the line of += in a loop?

payments.sum(&:price)


        
相关标签:
4条回答
  • 2020-12-04 02:57

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

    0 讨论(0)
  • 2020-12-04 02:59

    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.

    0 讨论(0)
  • 2020-12-04 03:00

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

    0 讨论(0)
  • 2020-12-04 03:05

    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

    0 讨论(0)
提交回复
热议问题