Adding Objects to an Array Question

The prompt is this:

“Q2: Write a method, sum which takes an array of numbers and returns the
sum of the numbers.”

Thus far, I have:

"def sum(nums)
total = 0

i = 0
while i < nums.count
total += nums[i]

i += 1

end
total
end

puts ‘Enter a series of numbers. Enter ‘Done’ when you are done.’
input = gets.chomp.to_i
while true
puts ‘Now another:’
input = gets.chomp
nums = []
nums.push input.to_i
if input.to_s == ‘Done’
nums.pop input.to_i
break
end
end

puts nums
sum(nums)"

I have been testing the program by inputting 1, then 2, then 3, and
finally Done. This has been the output:

“Enter a series of numbers. Enter ‘Done’ when you are done.
1
Now another:
2
Now another:
3
Now another:
Done
0”

I’m not sure if the inputs aren’t being added to the array, or if
inputting “Done” erases all objects in the array, or what. I’ll
appreciate any help in solving this :]

You set nums to an empty array INSIDE the loop. This means it’s cleared
every time.

When you see that the message “Done” is provided, you still convert it
to an integer, which will be 0. That’s why you end up with a zero in
your array at the end.

Rather than using “while true”, you can use “loop do” for an infinite
loop, which displays your intention better.

When you use “sum”, you don’t “puts” the result, so you won’t see it.

I’m not sure whether you’re supposed to do it a long way, but my
approach to getting the sum of all the numbers in an array would be
nums.reduce(&:+)

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs