For example
def test
a = "a is for apple"
def inner_method
a = "something" # this will refer to a different "a"
end
inner_method
puts a
end
Are there any reasons for this? Blocks have lexical scope, so why don't methods? Is this going to be fixed?
It's because Ruby's methods aren't first class objects (as they would be in IO, for example). So when you define the inner method, what is the receiver? Presumably the method itself, or the binding or something, but Ruby doesn't have that deep of OO.
Anyway, it's unclear to me what you were expecting to happen in your example, were you wanting it to modify the local variable a
? If so, a proc is a suitable substitute for a method.
def test
a = "a is for apple"
inner_method = lambda do
a = "something"
end
a # => "a is for apple"
inner_method.call
a # => "something"
end
test
"functional.rb" is a more extravagant example of this style of programming.
And "lambda, proc, and Proc.new" is a breakdown of Ruby's different types of closures.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With