Search code examples
rubylanguage-designsuper

Why is 'super' a keyword rather than a method in Ruby?


In Ruby, super is a keyword rather than a method.

Why was it designed this way?

Ruby's design tends toward implementing as much as possible as methods; keywords are usually reserved for language features that have their own grammar rules. super, however, looks and acts like a method call.

(I know it would be cumbersome to implement super in pure Ruby, since it would have to parse the method name out of caller, or use a trace_func. This alone wouldn't prevent it from being a method, because plenty of Kernel's methods are not implemented in pure Ruby.)


Solution

  • It behaves a little differently, in that if you don't pass arguments, all of the current arguments (and block, if present) are passed along... I'm not sure how that would work as a method.

    To give a rather contrived example:

    class A
      def example(a, b, c)
        yield whatever(a, b) + c
      end
    end
    
    class B < A
      def example(a, b, c)
        super * 2
      end
    end
    

    I did not need to handle the yield, or pass the arguments to super. In the cases where you specifically want to pass different arguments, then it behaves more like a method call. If you want to pass no arguments at all, you must pass empty parentheses (super()).

    It simply doesn't have quite the same behaviour as a method call.