Alexandre
Alexandre

Reputation: 13308

Variable defined inside loop in Ruby

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?

Upvotes: 1

Views: 567

Answers (1)

sepp2k
sepp2k

Reputation: 370152

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.

Upvotes: 6

Related Questions