Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Assuming that all parts are <a href="http://www.ruby-doc.org/core-1.9.3/Marshal.html#method-c-dump" rel="nofollow">serializable by <code>Marshal</code></a> and you want a completely deep clone:</p> <pre><code>class Object # This doesn't have to be on Object; it could be on KillerSudoku instead def deep_clone Marshal.load(Marshal.dump(self)) end end </code></pre> <p>Seen in action:</p> <pre><code>class KillerSudoku attr_accessor :cells end ks1 = KillerSudoku.new ks1.cells = ["one",2,3] ks2 = ks1.deep_clone ks2.cells.pop ks2.cells.first.reverse! p ks1.cells, ks2.cells #=&gt; ["one", 2, 3] #=&gt; ["eno", 2] # New array with all instance values being uniq, too </code></pre> <p>From the docs, the above won't work if you have any of the following in your structures:</p> <ul> <li><p>anonymous <code>Class</code> or <code>Module</code>.</p></li> <li><p>objects which are related to the system (e.g. <code>Dir</code>, <code>File::Stat</code>, <code>IO</code>, <code>File</code>, <code>Socket</code>, etc.)</p></li> <li><p>an instance of <code>MatchData</code>, <code>Data</code>, <code>Method</code>, <code>UnboundMethod</code>, <code>Proc</code>, <code>Thread</code>, <code>ThreadGroup</code>, <code>Continuation</code></p></li> <li><p>objects which define singleton methods</p></li> </ul> <hr> <p>As seen above, this is a truly deep clone, such that even strings become new instances. If you want the arrays of cells and zones to be cloned, but have all values still referencing the same objects, then you want to customize what <code>dup</code> and <code>clone</code> do by using <code>initialize_copy</code>:</p> <pre><code>class KillerSudoku attr_accessor :cells def initialize_copy(old) self.cells = old.cells.dup end end </code></pre> <p>Seen in action:</p> <pre><code>ks1 = KillerSudoku.new ks1.cells = ["one",2,3] ks2 = ks1.clone ks2.cells.pop ks2.cells.first.reverse! p ks1.cells, ks2.cells #=&gt; ["eno", 2, 3] #=&gt; ["eno", 2] # New array that references all the same objects </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload