Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum of instance variables in Array Ruby

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?

like image 684
NicoBar Avatar asked May 22 '26 20:05

NicoBar


2 Answers

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}"
like image 143
Tanmaya Avatar answered May 24 '26 13:05

Tanmaya


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}"
like image 34
Gabe Koss Avatar answered May 24 '26 15:05

Gabe Koss



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!