ThomasStringer
ThomasStringer

Reputation: 121

Summing all numbers in an array

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

Upvotes: 1

Views: 124

Answers (1)

PhilVarg
PhilVarg

Reputation: 4820

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(:+))

Upvotes: 4

Related Questions