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}"
This is a great opportunity to use something like inject. Starting with a sum of 0 you can do something like the following. This allows you to both printand work with the data item but also combine it with an arbitrary accumulator (in this case an integer that starts as 0).
print "Items:"
sum = item_list.inject(0) do |sum, item|
print " #{item.name},"
sum += item.price
end
puts "Total: #{sum}"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With