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

Understanding the "Until" loop

I'm working with the following bit of Ruby code:

name = ""

until name == "Jason" do 
    name = gets.chomp
    puts "Your name is: #{name}"
end

I understand that this loop will keep going until it's given "Jason". What I don't understand is why when I type "Jason", I still see the puts "Your name is: Jason" and then the program ends.

I'm wondering why the 'puts' method was used here, when one would think the loop wouldn't even run now that it's been given the value of "Jason" (so the next 2 lines wouldn't be used).

What am I not understanding?

3 Answers

Maybe this flowchart will help

  1. name is initalized to null
  2. check if name is set to "Jason"
  3. Since name is set to null continue into the until block
    1. Type "James" at the prompt
    2. parse "James" from input
    3. set name equal to James
    4. print the contents of name which is currently "James"
  4. check if name is set to "Jason"
  5. since name was set to "James" in step 3-3 continue into the until block
    1. Type "Jason" at the prompt
    2. parse "Jason" from input
    3. set name equal to Jason
    4. print the contents of name which is currently "Jason"
  6. check if name is set to "Jason"
  7. Since name is set to Jason in step 5-3 don't execute the until block

Oh, my duh! YES! Sigh, thank you sir - that makes total sense!

the loop is will always cycle through at least once as long as ur name is set to an empty string as you have done or something other than Jason. when ur trying to understand loops or any other methods just take some example inputs and go down the line and see what u get.

Hi James - That flowchart seems to prove my point. if name == Jason it jumps to "End". It doesn't get to "read name" or to "print name", so if I enter Jason the program should just end, not "Your name is Jason".

Andre' I'm not sure I understand what you're outlining.