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

Looping in Ruby

I want to loop through the code below until the user enters in a name with a minimum of 5 characters. Once they do, then I want the loop to break. Trying to figure out how to represent this in Ruby.

if player == ""
        puts "Not much of a talker eh?  Speak up please, couldn't hear you." 
        gets.chomp.downcase
end

Also want to loop through this one as well until the user selects something other than Michael Jordan. Once they do, I want the loop to break.

if player == "michael jordan"
            puts "Oh, how creative.  Other than him?  Pick again!"  
            player = gets.chomp.downcase
end

1 Answer

Here's a very basic example of a "Loop and a half" based on your first code snippet. It will repeatedly prompt for input and will only break when the word is longer than or equal to 5 characters:

puts "Please enter your name"

while true
  player = gets.chomp

  if player.length >= 5
    break
  end

  if player == ""
    puts "Not much of a talker eh?  Speak up please, couldn't hear you."
  else
    puts "Try again...we need at least 5 characters."
  end

end

while true makes it an infinite loop and inside you define a condition that will break it.

Thanks this works great! Any ideas for the 2nd one?

You would just need something like this instead of the if player == "" in my first example:

if player.downcase != "michael jordan"
    break
else
    puts "Oh, how creative.  Other than him?  Pick again!"
end

This will break the loop ONLY if the player is not "michael jordan" (with any lower and uppercase combination, because we downcase it anyway).

Play with them a bit on your own.