Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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,865 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!