Skip to content

Instantly share code, notes, and snippets.

@gravis
Created January 30, 2009 14:23
Show Gist options
  • Save gravis/55084 to your computer and use it in GitHub Desktop.
Save gravis/55084 to your computer and use it in GitHub Desktop.
Calculate sum of a Hashed cart
# make sure cart is composed of integers first.
# Without AR finding :
items = {1=>2, 3=>4}
price = 1.0
items.to_a.inject(0) {|sum,cart_item| sum + price * cart_item[1]}
# => 6.0
items.to_a.inject(0) {|sum,cart_item| sum + Product.find(@items[cart_item[0]],:select => :price).price * cart_item[1]}
# => 6.0
# if prices are all eq to 1.0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment