是否可以在Ruby中标识别名方法? [英] Is it possible to identify aliased methods in Ruby?
问题描述
通常在控制台中,我会询问一个对象
Often within the console, I'll interrogate an object
pp obj.methods.sort #or...
pp (obj.methods - Object.methods).sort
在Ruby中,这很常见开发人员为方法提供别名。我想知道是否有一种识别别名的反射方法,以便我可以显示别名方法,例如...
In Ruby it's pretty common for a developer to provide aliases for methods. I am wondering if there is a reflective way of identifying aliases so that I might be able to display aliased methods, something like...
array.aliased_methods #=> {:collect => :map, ...}
这将有助于准确识别
推荐答案
在Ruby 1.9中,别名实例方法将是 eql?
,因此您可以定义:
In Ruby 1.9, aliased instance methods will be eql?
, so you can define:
class Module
def aliased_methods
instance_methods.group_by{|m| instance_method(m)}.
map(&:last).keep_if{|symbols| symbols.length > 1}
end
end
现在,如果尝试,您将得到:
Now if you try it, you will get:
class Foo
def bar; 42 end
alias baz bar
def hello; 42 end
end
Foo.aliased_methods # => [[:bar, :baz]]
Array.aliased_methods # => [[:inspect, :to_s], [:length, :size]]
请注意,有些对丢失,例如 [:map,:collect]
。这是由于已修复的错误并将在下一版本(2.0 .0)如果对您很重要,则可以使用自己的 group_by
而不使用哈希或 eql?
使用 ==
。
Note that some pairs are missing, e.g. [:map, :collect]
. This is due to a bug that is now fixed and will be in the next version (2.0.0) If it is important to you, you can roll your own group_by
without using hashes or eql?
and only using ==
.
这篇关于是否可以在Ruby中标识别名方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!