Finding sum

Get a list of product ids from a form, then

sum the total price

product_list = params[:product_ids]
total = Product.find(product_list).sum(&:price)

I understand the first list line and part of the second line, but what
does the & symbol mean?
TIA.

Bala P. wrote:

Get a list of product ids from a form, then

sum the total price

product_list = params[:product_ids]
total = Product.find(product_list).sum(&:price)

I understand the first list line and part of the second line, but what
does the & symbol mean?

That converts the symbol into a block that sends the symbol to its
argument. Full explanation here:
http://blog.hasmanythrough.com/articles/2006/03/07/symbol-to-proc-shorthand


Josh S.
http://blog.hasmanythrough.com

sum(&:price) is effectively the same as sum { |p| p.price }, just
shorter.

http://dev.rubyonrails.org/browser/trunk/activesupport/lib/active_support/core_ext/symbol.rb

-Jonathan.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs