0

I think I know super intends to override the same method inherited from the parent class. However, in this below message passing code example, I don't know what is the supersupposed to do there:

class WellBehavedFooCatcher
    def respond_to?(method_name)
      if method_name.to_s[0,3] == "foo"
        true
      else
        super(method_name)
      end
    end
end

So what does superdo in the above code?

Thank you so much in advance!

Penny
  • 1,218
  • 1
  • 13
  • 32
  • 5
    A simple look at the Ruby docs would tell you what you need to know. Also possible duplicate of [Super keyword in Ruby](http://stackoverflow.com/q/4632224/2006429). – rgajrawala Mar 13 '16 at 06:46

2 Answers2

2

How super uses arguments:

  • super - Forwards all the arguments.
  • super() - No arguments are forwarded.
  • super(arg1,arg2) - Only arg1 and arg2 are forwarded.

Called with an argument (in this case method_name), super only sends this argument to the next respond_to? method it finds via the method-look-up path. In this case since super has the one and only argument, super and super(method_name) behave in the same way.

The next respond_to? method is most likely the original respond_to? method which is located in the Kernel module which is included in the Object class.

Kernel.methods.include?(:include?) #=> true
Sagar Pandya
  • 9,323
  • 2
  • 24
  • 35
2

I think I know super intends to override the same method inherited from the parent class.

Actually, it is the opposite. When you override some method in a child class, super is used to refer to the behaviour of the same method in the parent class (i.e., the original behaviour).

In the given code, the indent is to make it dynamically respondable to any method that starts with foo without changing the respondability of other methods. The first part is done by:

if method_name.to_s[0,3] == "foo"
  true

but if it were only that, all other undefined methods would simply return nil even if they are defined in some parent class. If some parent class were to respond to such method, then returning nil to respondability would incorrectly block such methods. The other part:

else
  super(method_name)

is to return the correct value for such case. It means that in other cases, do what the parent class did.

sawa
  • 165,429
  • 45
  • 277
  • 381
  • Thank you @sawa, but what is the parent class? for example, the following exercise: `catcher.respond_to?(:something_else)` equals to false...I don't know why with `super(method_name)`, the answer is false? – Penny Mar 13 '16 at 22:50
  • Parent is `Object` by default. – sawa Mar 14 '16 at 03:46