What are the uses of ruby's Hash.replace or Array.replace?

arrays, hash, replace, ruby

Solution

I think the intended use is to modify an array in-place that has been passed to a method. For example:

def m(a)
    a.replace(%w[a b])
end

a = %w[x y z]
m(a)
# a is now ['a', 'b']

Without `replace`, you'd have to do something like this:

def m(a)
    a.clear
    a << 'a' # or use .push of course
    a << 'b'
end

Using `replace` lets 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.

Problem

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?

Original source