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 Ruby Loops Ruby Loops The Ruby Loop

Why is my code endless looping and not stopping at the correct array?

My code goes through an endless loop but doesn't make the array = 3 numbers. What's going on?

loop.rb
numbers = []

number = 0

# write your loop here
loop do
  numbers.push(number)
  numbers.push(number + 1)
  number = number + 1
  if numbers.length == 3
  break
  end
end

2 Answers

You're pushing to the numbers array twice in each loop, then checking only to see if numbers == 3

So you're pushing 2 items (length == 2) then 2 items (length == 4)

...and just leaping right over 3. :)

numbers = []

number = 0

# write your loop here
loop do
  numbers.push(number)  # push one item...
  numbers.push(number + 1)  # then push another...
  number = number + 1
  if numbers.length == 3
    break
  end
end

Thanks Gavin! That was it. Got it going.

Fantastic