Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 728
icanhazbroccoli Avatar asked Jul 03 '11 00:07

icanhazbroccoli


People also ask

Does order matter in Ruby?

You could define method in any order, the order doesn't matter anything.

What is Define_method in Ruby?

define_method is a method defined in Module class which you can use to create methods dynamically. To use define_method , you call it with the name of the new method and a block where the parameters of the block become the parameters of the new method.


2 Answers

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 
like image 172
Mark Thomas Avatar answered Sep 22 '22 06:09

Mark Thomas


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
like image 20
Vasfed Avatar answered Sep 26 '22 06:09

Vasfed