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

前端 未结 4 636

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

提交回复
热议问题