Note that there are some explanatory texts on larger screens.

plurals
  1. POIsolating Ruby methods from overriding in subclasses? (like Java's private methods)
    primarykey
    data
    text
    <p>In Ruby, I'd like to acheive something like this Java sample:</p> <pre><code>class A { private void f() { System.out.println("Hello world"); } public void g() { f(); } } class B extends A { public void f() { throw new RuntimeException("bad guy");} } public class Try { public static void main(String[] args) { new B().g();} } </code></pre> <p>This will print "Hello world" in Java, but the straight Ruby transcript:</p> <pre><code>class A def g; f; end private def f; puts "Hello world"; end end class B &lt; A def f; raise "bad guy"; end end B.new.g # want greet </code></pre> <p>will of course raise a bad guy - due to differences in method lookup mechanism (I realise the meaning of 'private' is very different between these languages)</p> <p>Is there any way to achieve a similar effect? I don't really care about visibility, would actually prefer all public methods here. My goal is simply to isolate a method in the superclass from overriding in subclasses (which would break the other base methods).</p> <p>I guess if there is a solution, that would work with modules/includes, too?</p> <pre><code>module BaseAPI def f; puts "Hello world"; end def g; f; end; end module ExtAPI include BaseAPI # some magic here to isolate base method :f from the following one? def f; raise "bad guy"; end # could actually be something useful, but interfering with base 'g' end include ExtAPI g # want greet </code></pre> <hr> <p>Follow-up: this looks to be the rare case where something is possible with Java but not with Ruby :-/</p>
    singulars
    1. This table or related slice is empty.
    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