'Is there any way to get all the method's aliases in Ruby?

Suppose I've got a class:

class MyClass
  def my_method
    # cool stuff
  end
  alias :my_method2 :method
end

And now I want to get all the aliases for method my_method without comparison with all the object methods.



Solution 1:[1]

I'm not sure how to do it without using comparisons. However, if you remove Object.methods you can limit the comparisons made:

def aliased?(x)
  (methods - Object.methods).each do |m|
    next if m.to_s == x.to_s
    return true if method(m.to_sym) == method(x.to_sym)
  end
  false
end 

Solution 2:[2]

A bit of a hack, but seems to work in 1.9.2 (but does not in 1.8 etc.):

 def is_alias obj, meth
   obj.method(meth).inspect =~ /#<Method:\s+(\w+)#(.+)>/
   $2 != meth.to_s
 end

Solution 3:[3]

MyClass.instance_methods(false) will give you just the instance methods defined for your class. This is a good way to get rid of any ancestor methods. In your case, the only methods that should show up are my_method and my_method2.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mark Thomas
Solution 2 Vasfed
Solution 3 bheeshmar