/ Published in: Ruby
This will add up all the prices and return it? What does |item| mean exactly?
Expand |
Embed | Plain Text
@items.sum { |item| item.price }
Comments
Subscribe to comments
You need to login to post a comment.
wackimonki on 02/26/07
rails rubyonrails adding question
2 people have marked this snippet as a favorite
This will add up all the prices and return it? What does |item| mean exactly?
@items.sum { |item| item.price }
Subscribe to comments
You need to login to post a comment.
A little explanation to how the code works.
The method, sum, calls the block as often as it likes, with arguments. The block does something with the arguments and returns a value to the method.
In this case, .sum method calls the block for each item, and the block returns the price for the item to the .sum method.