Use [].replace to make a copy of an array

前端 未结 2 1619
星月不相逢
星月不相逢 2021-01-16 07:49

I have a class where I was using the Array#shift instance method on an instance variable. I thought I made a \"copy\" of my instance variable but in fact I hadn

2条回答
  •  醉话见心
    2021-01-16 08:08

    The preferred method is dup

    • use array.dup whenever you need to copy an array
    • use array.map(&:dup) whenever you need to copy a 2D array

    Don't use the marshalling trick unless you really want to deep copy an entire object graph. Usually you want to copy the arrays only but not the contained elements.

提交回复
热议问题