I always see replace in the Array and Hash documentation and I always think that it’s odd.
I’m sure I’ve done something like this many times:
a = [:a, :b, :c, :d]
...
if some_condition
a = [:e, :f]
end
But I never thought to use this instead:
a = [:a, :b, :c, :d]
...
if some_condition
a.replace [:e, :f]
end
Which I assume is the intended use. Does this really save memory, or have some other benefit, or is it just a style thing?
I think the intended use is to modify an array in-place that has been passed to a method. For example:
Without
replace, you’d have to do something like this:Using
replacelets you do it all at once should bypass the auto-shrinking and auto-growing (which probably involves copying some memory) behavior that would be a side effect of replacing the array’s content (not the array itself!) element by element. The performance benefit (if any) is probably just an extra, the primary intent is probably to get pointer-to-pointer behavior without having to introduce pointers or wrap the array in an extra object.