Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The thing is, the return value of <code>initialize</code> is ignored. here's what happens when you call <code>A.new</code>:</p> <ul> <li><code>new</code> calls a special class method called <code>allocate</code> -- this returns an empty instance of the class</li> <li><code>new</code> then calls <code>initialize</code> on the object returned by <code>allocate</code>, and returns the object</li> </ul> <p>To do what you want to do, you need to override <code>new</code> and make it do what you want:</p> <pre><code>class A def self.new(args*) if(args[0]==1) B.new(*args[1..-1]) else C.new(*args[1..-1]) end end end </code></pre> <p>There is something else to consider though. If <code>A</code> is never really used on its own, you should be using some sort of factory method, or, just a simple if statement. Eg:</p> <pre><code>def B_or_C(param,args) (param == 1 ? B : C).new(args) end </code></pre> <p>The design really depends on what you are using them for. When you, for example, have a class that could be used to handle multiple versions of something, for example, HTML, you could have a main class <code>HTMLParser</code> which overrode <code>new</code> and could return any of its subclasses: <code>HTML1Parser</code>, <code>HTML2Parser</code>, <code>HTML3Parser</code>, <code>HTML4Parser</code>, and <code>HTML5Parser</code>.</p> <p>Note: You have to override the <code>new</code> method to the default in the sub-classes to prevent infinite looping:</p> <pre><code>def self.new(args*) obj=allocate obj.send(:initialize, *args) obj end </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. 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.
 

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