I have an array item_list = [item1, item2, item3,] that stores objects that have prices. I would like to do the sum of those prices and display it as a Total.
I tried to do this:
print "Items:"
item_list.each do |item|
print " #{item.name},"
prices_arr = []
prices_arr << item.price
sum = prices_arr.sum
end
puts "Total: #{sum}"
But I get the error, undefined local variable or method `sum'. If I put "Total: #{sum}" in the loop it will give me each item followed by its price but not a total. Any thoughts?
The problem with your approach is that the variable sum is defined inside the loop, and that is why its scope is limited inside that
print "Items:"
item_list.each do |item|
print " #{item.name},"
prices_arr = []
prices_arr << item.price
sum = prices_arr.sum
end
puts "Total: #{sum}"
So, a better way would be :-
sum = 0
print "Items:"
item_list.each do |item|
print " #{item.name},"
sum += item.price
end
puts "Total: #{sum}"