Coming from a JavaScript background I've become accustomed to being able to use JavaScript's dynamic scope to encapsulate values in a function. For example:
function Dog( firstname, lastname ) {
this.fullname = firstname + lastname
return {
say_name: function () {
return fullname;
}
}
}
Now in Ruby I'm not so sure something like this would work too well:
class Foo
attr_accessor :bar, :baz
def initialize bar, baz
@bar = bar
@baz = baz
end
def give_me_a_proc
return Proc.new { @bar + @baz }
end
end
Can anyone give a quick explanation of how scope works in Ruby? If I call the Proc returned from give_me_a_proc
, will it still have access to its define-time scope?
Also do the values become fixed once I define the proc or do any changes made in Foo
get carried down to the Proc even after it has been defined?
Yes, it will still have access to definition time scope. See documentation for Proc class.
Changes are carried down to the Proc post-definition. Results from irb run with your class.
> foo = Foo.new(1, 2)
=> #<Foo:0x007f9002167080 @bar=1, @baz=2>
> quux = foo.give_me_a_proc
=> #<Proc:0x007f900214f688@(irb):11>
> quux.call
=> 3
> foo.bar = 3
=> 3
> quux.call
=> 5
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