2

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

1
  • 6
    As you mentioned while, until, and for are keywords and do not create a local variable scope. loop on the other hand is a method call implemented as Kernel#loop and it adheres to the same lexical block scoping as other block calls in ruby. Commented Dec 14, 2021 at 16:22

1 Answer 1

1

but as i said before the do..end that follows while, until, or for loops don't create their own inner scope

Exactly. But there is no while, until, or for loop in your code.

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.