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?
In Ruby a proc is a closure. In Javascript, a function is a closure. The idea of a closure is that it “closes over” the environment in which it was defined. In Ruby the variables in the proc can still be changed, even by code living outside of the proc, and the new values will be reflected within the proc(see peakxu for demonstration). Not sure if Javascript closures work this way.