Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I don't really know what you are trying to do here - all the code you posted works on <em>instance</em> variables. Instance variables are per-object, not per class, so I don't know what you mean when you say "I need a value from the parent class".</p> <p>There are several things that I note with your code:</p> <ul> <li>Base classes should <strong>never</strong> be aware of subclasses. So creating <code>B</code> objects in <code>A#initialize</code> is not a good thing, because the base uses the subclass. </li> <li>You are overwriting the class <code>B#initialize</code> with a completely different behaviour than <code>A#initialize</code>. <s>You even change the parameter list. Not a very good thing either.</s> An object of a subclass should behave in the same way as an object of its superclass.</li> <li>When you call <code>B.new('myname')</code> the variable <code>@name</code> is never assigned, because the <code>A#initialize</code> method is never called. You will have to either call <code>super(:name =&gt; name)</code> (to run the superclass <code>initialize</code>) or you have to assign to <code>@name</code> directly in <code>B#initialize</code></li> <li>Once <code>@name</code> is defined, all your instance methods can use its value. Including the ones that are defined in the parent/superclass. </li> </ul> <p>Let me say I'm not quite sure why you are using inheritance here, I have the feeling that it is not what you want. If you have two classes for two <em>different</em> things, there should <strong>never</strong> be inheritance involved. If you want to re-use code, either have a look at Ruby's mixin feature, or compose your complex objects of several "smaller" objects that have the behaviour you want to re-use.</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.
    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.
    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