Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Ruby

Patrick Shushereba
Patrick Shushereba
10,911 Points

Sum Program

I'm trying to write a program that will sum numbers up to the input number n. I've been able to push the numbers into an array, but I haven't been able to successfully sum the numbers up. I tried to use the inject method, but it's not giving me any response.

Here's what I have so far:

print "Enter a number to sum up to:"
n = gets.chomp.to_i

num_array = []

i = 1
while i <= n
num_array.push(i)
i += 1
end

num_array.inject(:+)
puts num_array

1 Answer

You were so close!

Right now you're printing out the num_array which is the array you're building.

You should try printing the num_array.inject(:+) and you'll find that you're getting the sum correctly.

Patrick Shushereba
Patrick Shushereba
10,911 Points

Thanks a lot! I can't believe it was that simple. Honestly I'm just happy I got it working. It's hard being new to programming.