8 views
a = "outer"
1.times do
a = "inner"
end
a # => ???
The correct answer is
"outer"
"inner"
nil
Subscribe to RubyCademy and get free access to all our courses, plus hundreds of fun Ruby cards, quizzes, guides, and tutorials!
a = "outer" 1.times do a = "inner" end a # => "inner"
The variable a
is initialized outside of the block with the value "outer"
.
a = "outer"
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
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
.
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"
Subscribe to RubyCademy and get free access to all our courses, plus hundreds of fun Ruby cards, quizzes, guides, and tutorials!
RubyCademy ©