1 minute read

I noticed an interesting quirk of the alias method. Normally, if we call super from a method, it calls a method with the same name on the super class. However, if we alias a method and then call the new name, it calls the old super method.

For example, lets define a parent and child class. Both have a talk method:

class Parent
  def talk
    puts "Parent is talking"
  end
end

class Child < Parent
  def talk
    super
  end
end

Calling talk on the child calls talk on the Parent:

> c = Child.new
> c.talk
Parent is talking
=> nil

Now, we can modify Child and alias talk to shout:

Child.class_eval do
  alias :shout :talk
end

Now, here is the strange part. When we call shout on the child, it still calls talk on the parent, even though the method has a different name:

> c = Child.new
> c.shout
Parent is talking
=> nil

It appears that when we alias a method, it merely copies the super pointer, rather than resolving it on the fly.

However, if we unbind and rebind shout, then the call fails in the expected way:

> shout = Child.instance_method :shout
> shout.bind(c).call
NoMethodError: super: no superclass method `shout'
        from (irb):33:in `talk'

Updated: