Suppose I've got a class:
class MyClass
def my_method
# cool stuff
end
alias :my_method2 :method
end
开发者_Go百科And now I want to get all the aliases for method my_method without comparison with all the object methods.
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
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
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
.
精彩评论