Note that there are some explanatory texts on larger screens.

plurals
  1. POCopy/Inheritance of Ruby Matrix class (core/std lib)
    primarykey
    data
    text
    <p>I tried to extend an existing Singleton class in Ruby, as an example the Matrix class.</p> <p>My first <em>quick&amp;dirty</em> solution was a monkey patch (reopen class and extend with functionality).</p> <p>But I think, monkey patching in general isn't good, especially if someone tries to overwrite basic methods of core classes like in String, Integer, ...</p> <p>Next step was to find out, how I can get a real hard copy of the Matrix class with a new name (like MatrixExt) which behaves as a standalone singleton.</p> <pre class="lang-rb prettyprint-override"><code>MatrixExt = Matrix </code></pre> <p>didn't the job, as it results in:</p> <pre class="lang-rb prettyprint-override"><code>MatrixExt.scalar(2,0) =&gt; Matrix[[0, 0], [0, 0]] </code></pre> <p>So I only get multiple names for same singleton. Not, what I want.</p> <p>Same result with the <code>clone</code> and the <code>dup</code> methods.</p> <p>Also class inheritance won't work:</p> <pre class="lang-rb prettyprint-override"><code>class MatrixExt &lt; Matrix # patches ... end MatrixExt.scalar(2,0) =&gt; Matrix[[0, 0], [0, 0]] </code></pre> <p>And that was the most confusing part, because in self defined classes it is possible to get an inherited class. (So, why the core/std lib classes work different?)</p> <p>My current solution is to have a module with extension and then explicitly use <code>.extend</code> after initializing, like:</p> <pre class="lang-rb prettyprint-override"><code>m = Matrix.scalar(2,0).extend(MatrixExtModule) </code></pre> <p>That is okay for now, but my question is:</p> <p><strong>IS there another solution and -when yes- how to do it?</strong></p> <p><em>(No, copying the matrix.rb is not a good way, of course. ;o)</em></p> <p><strong>What I do wrong or where I think in a wrong way?</strong></p> <p>Thanks in advance for any solution and/or food for thoughts!</p>
    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.
 

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