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

Joshua Montmeny
PLUS
Joshua Montmeny
Courses Plus Student 6,135 Points

Why must there be a variable with an empty string before a loop in ruby?

In the following code, just above the while loop, answer is set to equal "" (an empty string). I'm not entirely sure why that's necessary, could someone please explain?

def add_contact
  contact = {"name" => "", "phone_numbers" => []}
  contact["name"] = ask("What is the persons name?")
  answer = ""
  while answer != "n"
    answer = ask("Do you want to add a phone nubmer? (y/n)")
    if answer.downcase == "y"
      phone = ask("Enter a phone number: ")
      contact["phone_numbers"].push(phone)
    end
  end
  return contact
end

Thanks much!

1 Answer

Hey Joshua,

In this case, take a look at your while loop. The loop is to continue running as long as answer is not equal to "n". If you do not initialize the variable answer before the loop, you'd receive an error stating that you have an undefined local variable. Which basically means that the variable answer hasn't been defined before the loop.

With that being said, you could technically set answer to something other than an empty string (Other than "n") and still have the loop run.

In any case, consider scope. Scope is the context in which a name has meaning.