Is it possible to identify aliased methods in Ruby

2019-01-18 22:37发布

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.

标签: ruby alias
2条回答
仙女界的扛把子
2楼-- · 2019-01-18 23:03

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

查看更多
甜甜的少女心
3楼-- · 2019-01-18 23:09

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.

查看更多
登录 后发表回答