title: Use [].replace to make a copy of an array
body: <p>I have a class where I was using the <code>Array#shift</code> instance method on an instance variable. I thought I made a "copy" of my instance variable but in fact I hadn't and <code>shift</code> was actually changing the instance variables.</p>
  
  <p>For example, before I would have expected to get <code>["foo", "bar", "baz"]</code> both times given the following:</p>
  
  <pre><code>class Foo
    attr_reader :arr
    def initialize arr
      @arr = arr
    end
  
    def some_method
      foo = arr
      foo.shift
    end
  end
  
  foo = Foo.new %w(foo bar baz)
  p foo.arr #=&gt; ["foo", "bar", "baz"]
  foo.some_method
  p foo.arr #=&gt; ["bar", "baz"]
  </code></pre>
  
  <p>result:</p>
  
  <pre><code>["foo", "bar", "baz"]
  ["bar", "baz"]
  </code></pre>
  
  <p>But as shown my "copy" wasn't really a copy at all. Now, I'm not sure if I should be calling what I want a "copy", "clone", "dup", "deep clone", "deep dup", "frozen clone", etc...</p>
  
  <p>I was really confused about what to search for and found a bunch of crazy attempts to do what seems like "making a copy of an array".</p>
  
  <p>Then I found <a href="https://stackoverflow.com/a/41500298/2909897">another answer</a> with literally one line that solved my problem:</p>
  
  <pre><code>class Foo
    attr_reader :arr
    def initialize arr
      @arr = arr
    end
  
    def some_method
      foo = [].replace arr
      foo.shift
    end
  end
  
  foo = Foo.new %w(foo bar baz)
  p foo.arr #=&gt; ["foo", "bar", "baz"]
  foo.some_method
  p foo.arr #=&gt; ["foo", "bar", "baz"]
  </code></pre>
  
  <p>output:</p>
  
  <pre><code>["foo", "bar", "baz"]
  ["foo", "bar", "baz"]
  </code></pre>
  
  <p>I understand that <code>Array#replace</code> is an instance method being called on an instance of <code>Array</code> that happens to be an empty array (so for example <code>foo = ["cats", "and", "dogs"].replace arr</code> will still work) and it makes sense that I get a "copy" of the instance variable <code>@arr</code>.</p>
  
  <p>But how is that different than:</p>
  
  <pre><code>foo = arr
  foo = arr.clone
  foo = arr.dup
  foo = arr.deep_clone
  Marshal.load # something something
  # etc...
  </code></pre>
  
  <p>Or any of the other crazy combinations of <code>dup</code> and <code>map</code> and <code>inject</code> that I'm seeing on SO?</p>