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.
You could define method in any order, the order doesn't matter anything.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With