I'm struggling with variable scope within a block in ruby. I learnt that do..end that follows while, until, or for loops are not blocks because while, until, or for are not method calls. So they don't create their own inner scope. but this example confused me
loop do
b = 2
p b # => 2
break
end
p b
Here in this example b is initialized with the number 2 inside the do..end. The puts method is called with the variable b passed to it as an argument, and it through an NameError. saying that b is undefined local variable, but as i said before the
do..end that follows while, until, or for loops don't create their own inner scope
while,until, andforare keywords and do not create a local variable scope.loopon the other hand is a method call implemented asKernel#loopand it adheres to the same lexical block scoping as other block calls in ruby.