Sum

OK im stuck again… I am following the agile web development with rails
book and after i made the cart i get an error:

undefined method `sum’ for #Array:0x8ca5e24

the code i have in cart.rb is:
def total_price
@items.sum { |item| item.price }
end

and in view I have:

Your Cart
<% for cart_item in @cart.items %> <% end %>
<%= cart_item.quantity %>× <%= h(cart_item.title) %> <%= number_to_currency(cart_item.price) %>
Total <%= number_to_currency(@cart.total_price) %>

<%= button_to “Empty cart”, :action => :empty_cart %>

Eric wrote:

OK im stuck again… I am following the agile web development with rails
book and after i made the cart i get an error:

undefined method `sum’ for #Array:0x8ca5e24

the code i have in cart.rb is:
def total_price
@items.sum { |item| item.price }
end

the view is not important. the idea is that sum is not a known method
for an array. by dropping the ‘sum’ method and doing this action
yourself in the total_price action like:

def total_price
total=0
@items.each {|item| total += item.price }
total
end

you should be getting the same effect.
you may like to define ‘sum’ in the Array Class, but that may be too
much for the given task, so i believe the above should be enough.
hope it helps, somewhat.

harp

From the most recent update to the Agile2 PDF:

“I need to stress that the book is written on the assumption that the
reader
has Rails 1.2 installed. As that doesn’t yet exist, you HAVE TO HAVE
EDGE
RAILS for some of this stuff to work.” - Dave T.

This cart/sum thing is coming up a lot the last couple of days. The
good
thing is that instead of just copying lines out of a book, the tutorial
makes you figure out alternate ways of doing things when they don’t
work.
The bad thing is there are a lot of people just starting out, getting
really
frustrated.

–f