1

I want to put a possibly infinite amount of numbers in and then it's added to an array, which is then all added together.

I saw this on a few other questions but they were all just puts-ing the array, not summing.

case input
 when 'add'
 puts "Enter the numbers to add on separate lines then hit enter on another line"
 add_array = []
 numbers_to_add = " "
 while numbers_to_add != ""
  numbers_to_add = gets.chomp
  add_array.push numbers_to_add
 end
 add_array.delete('')
 add_array.map(&:to_f).inject(:+)
 puts add_array
end
the Tin Man
  • 158,662
  • 42
  • 215
  • 303
ThomasStringer
  • 121
  • 1
  • 8

1 Answers1

4

You can utilize the inject method.

[1,2,3].inject(:+) #=> 6

By the looks of your code I'd guess that your incoming array is an array of strings, not an array of numbers. To convert them to decimals (floats) you can use:

sum = add_array.map(&:to_f).inject(:+)
puts sum

This applies the #to_f operation on every element, then passes that to the summing function (#inject(:+))

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
PhilVarg
  • 4,762
  • 2
  • 19
  • 37