Block & outer vars

8 views

a = "outer"
1.times do
a = "inner"
end

a # => ???

The correct answer is

"outer"

"inner"

nil

Unlock Your Ruby Potential

Subscribe to RubyCademy and get free access to all our courses, plus hundreds of fun Ruby cards, quizzes, guides, and tutorials!

Explanation

a = "outer"
1.times do
  a = "inner"
end

a # => "inner"

Variable Initialization

The variable a is initialized outside of the block with the value "outer".

a = "outer"

Block Execution

The block 1.times do ... end is executed once (since .times iterates the specified number of times—in this case, once).

Inside the block, the variable a is assigned a new value "inner".

1.times do
  a = "inner"
end

What Happens to a Inside the Block?

In Ruby, local variables inside blocks can access and modify variables from the outer scope. The a inside the block is not a new variable—it refers to the same a that was defined before the block.

Therefore, the assignment a = "inner" modifies the outer a.

Final Value of a

After the block completes, the variable a retains its new value "inner" because the modification inside the block is reflected in the outer scope.

a # => "inner"

Key Takeaways:

  • Ruby's block scoping: Ruby allows blocks to access and modify local variables from their enclosing scope. This is different from some other languages where blocks introduce a new scope for variables.
  • Variable mutation within a block: If you modify a variable inside a block, the modification is reflected outside of the block as well.

Unlock Your Ruby Potential

Subscribe to RubyCademy and get free access to all our courses, plus hundreds of fun Ruby cards, quizzes, guides, and tutorials!

RubyCademy ©