Is there a way to get all method aliases in Ruby?

Suppose I have 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 the my_method method without comparing with all the object methods.

+4
source share
3 answers

I am not sure how to do this without using comparisons. However, if you delete 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 
+2
source

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

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

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

0
source

All Articles