Saturday, 28 September 2013

Ruby References

Ruby References

When I have the following method:
def n_times(thing)
lambda { |n| thing * n }
end
and I call it like that:
x = [:a]
p1 = n_times(x)
x = [:b]
p p1.call(3) # => [:a, :a, :a]
x will not be changed, the output will be [:a]. Why?
Because when doing something like .pop instead, x will be changed:
x = [:a]
p1 = n_times(x)
x.pop
p p1.call(3) # => []
Is it because [:b] is a new object?

No comments:

Post a Comment