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

Quick Loops question

In the Ruby Loops tutorial:

name = ""

loop do 
    print "Enter your name: "
    name = gets.chomp
    if name == "Andy"
        puts "Hi #{name}, we've been expecting you..."
        break
    end
end

Why does he bother creating the name variable before the loop? The code seems to work just fine without it?

1 Answer

Hi Andrew, I believe it has to do with scope. It works this way because you have only one loop, but if you want to access "name" from another block outside of the loop, without it being previously defined outside of the loop you might not be able to access it because its scope would be limited in that loop. You can read more on that here Variable Scope and Loops .

So it's simply a 'best practice thing', but not necessary in this example.

Exactly :)