Is it possible to identify aliased methods in Ruby

2019-01-18 23:13发布

问题:

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_methods #=> {:collect => :map, ...}

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

回答1:

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



回答2:

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.



标签: ruby alias