1

Here is a while loop in Ruby

x = 0
while x < 1 do
   inside_var = "I'm inside"
   x += 1
end

puts inside_var

Although, inside_var is defined inside a while loop, it's visible outside of it. It's totally different from Java, C#, etc.

I wonder, did I miss something? Is it really how it works? Is it true for any kind of loop in Ruby?

1
  • Yes, that's how it works. Variables defined in a loop are scoped to the containing function. Commented Jan 6, 2013 at 13:44

1 Answer 1

6

Yes, it really is how it works. It applies to all built-in control structures (while, for, if, begin ... end), but not to blocks. So if you rewrite your code using each or times, it will behave like you expect.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.