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

Jon Thomas
Jon Thomas
8,916 Points

Problem solving Ruby loop challenge

I can't seem to solve the loop challenge for Ruby. I've attached my code. What am I doing wrong here?

loop.rb
numbers = []

number = 0

# write your loop here
loop do
  numbers.push(number)
  number += 1
  if numbers.length > 3
    break
  end
end
Jon Thomas
Jon Thomas
8,916 Points

Ok, I see the problem. I was pushing to numbers for a 4th time, so the length was 4, not 3. I do think the challenge text is a little confusing though, since it says "greater than 3".

3 Answers

Kevin Mulhern
Kevin Mulhern
20,374 Points

Hey Jon, the if statement will break the loop when there are more than three elements in the array, so it will break when 4 elements are in the array. To pass the challenge you need to break when there are exactly three elements in the array so all you have to do is change your if statement so that it breaks the loop when the array length is greater than or equal to 3. The code below will make it work.

if numbers.length >= 3

Try adding an else to your if statement:

numbers = []

number = 0

# write your loop here
loop do
  numbers.push(number)
  number += 1
  if numbers.length > 3
    break
  else
  end
end
William Li
William Li
Courses Plus Student 26,868 Points

the problem here is the if conditional, like Kevin Mulhern has previously pointed out, so adding else won't fix the issue here.

Jon Thomas
Jon Thomas
8,916 Points

Thanks for clarifying even further Kevin!