开发者

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

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_meth开发者_StackOverflowods #=> {:collect => :map, ...}

This would be helpful for being able to identify exactly how many things an object can do.


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]]

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 ==.


Not really. Alias isn't just a pointer or something like that, after an alias you can undef the first method and the aliased method won't change (think hard link vs sym link). Typically, aliases are reflected in the rdoc, so I would go there for a definitive list.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜