Lambda local variable default value fails to use the closured local variable

139 views Asked by At

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?

1

There are 1 answers

8
joanbm On BEST ANSWER
λ = ->(x = x) {…}

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 original x.

For default value you may use distinct local variable name, instance variable or if insist, get outer x through Binding#local_variable_get.