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 Loop Conditionals

Why is the print "Enter your name..." and name = gets.chomp in the loop? They're not needed for looping.

I pulled the print and gets.chomp out and it works fine. They aren't really necessary in looping, unless I'm missing something obvious.

def get_name
  print "Enter your name (minimum 2 characters, no numbers): "
  name = gets.chomp

  loop do
    if name.length >= 2 && !name.index(/\d/)
      break
    else
      puts "Name must be longer than 2 characters and not contain numbers."
    end
  end
  return name
end

name = get_name()
puts "Hi #{name}."

Print and setting the variable name is not part of the loop. It places the data that you received into the variable name and does loop around the variable name.

The loop part of this method checks if character is less than 2 characters and returns if greater than 2 characters.

1 Answer

Freddy Heppell
Freddy Heppell
9,753 Points

The reason for this is so that it continually prompts you for your name until it meets the requirement of more than two characters.

Try entering a name of less than two characters, what happens?

  1. You enter the name "a"
  2. The loop starts
  3. The name is less than two characters, so it prints the warning
  4. The loop runs again
  5. The name is still less than two characters, so it prints the warning
  6. The loop runs again
  7. The name is still less than two characters, so it prints the warning

This will repeat forever, you have created an infinite loop.

The reason that the name request is in the loop is so, if the name is formatted incorrectly, it can ask you again, and repeatedly ask you until you have entered a valid username. Hope this helps.