Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I think you have the wrong concept here. Classes in Ruby are similar to classes in Java, Smalltalk, C#, ... and all are templates for their instances. So the class defines the structure and the behavior if its instances, and the parts of the structure and behavior of the instances of its subclasses <strong>but not vice versae</strong>.</p> <p>So direct access from a superclass to a constant in a subclass is not possible at all, and that is a good thing. See below how to fix it. For your classes defined, the following things are true:</p> <ul> <li><code>class Animal</code> defines the method <code>make_noise</code>.</li> <li>instances of <code>class Animal</code> may call the method <code>make_noise</code>.</li> <li><code>class Dog</code>defines the constant <code>NOISE</code> with its value.</li> <li>instances of <code>Dog</code> and the class <code>Dog</code> itself may use the constant <code>NOISE</code>.</li> </ul> <p>What is not possible:</p> <ul> <li>Instances of <code>Animal</code> or the class <code>Animal</code> itself have access to constants of the class <code>Dog</code>.</li> </ul> <p>You may fix that by the following change:</p> <pre><code>class Animal def make_noise print Dog::NOISE end end </code></pre> <p>But this is bad style, because now, your superclass (which is an abstraction about <code>Dog</code> and other animals) knows now something that belongs to <code>Dog</code>.</p> <p>A better solution would be:</p> <ol> <li>Define an abstract method in class <code>Animal</code> which defines that <code>make_noise</code> should be defined. See the answer <a href="https://stackoverflow.com/a/6792499/41540">https://stackoverflow.com/a/6792499/41540</a>.</li> <li>Define in your concrete classes the method again, but now with the reference to the constant.</li> </ol>
    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.
 

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