Consider the following piece of code:
x = 1
λ = ->(x = x) { puts "[#{x}]"; x = 2; puts "[#{x}]" }
I would expect that the value of the topmost level local variable x
will be used as a default value for the lambda’s local variable x
. That said, the code above should be more or less equivalent to:
λ = ->(x = 1) { puts "[#{x}]"; x = 2; puts "[#{x}]" }
Unfortunately, that is not the case: (x = x)
is not treated that way and lambda’s local x
is being initially set to nil
:
λ.()
#⇒ []
# [2]
Why the RHO in (x = x)
is not taken from the outermost binding
?
In above code
x
argument identifier overshadows current scope local variable of the same name, so default value already refers to this argument and not originalx
.For default value you may use distinct local variable name, instance variable or if insist, get outer
x
throughBinding#local_variable_get
.