In the following code, a
is initialized outside of times
, but times
creates an inner scope, and a
is accessible:
a = 5
3.times do |n|
a = 3
end
a # => 3
The return value of a
is 3
because a
is available from the scope created by 3.times do ... end
, which allows re-assigning the value of a
. In fact, it re-assigned a
to 3
three times.
Why is the following different from above?
a = 5
def adder(num)
num = 3
end
adder(a) # => 3
a # => 5
It is because we bring in a
, but it does not change the local variable, maybe because its a method. I don't know. Why is a
5
and not 3
?