tags:

views:

43

answers:

2

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.

A: 

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.

Matt Briggs
+2  A: 

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]. That seems to be due to the fact that length and size are defined as aliases but map and collect are simply defined as having the same implementation (see here and two lines below). I'll open an issue on redmine when I get a second, but if it is important to you, you can roll your own group_by without using hashes or eql? and only using ==.

Marc-André Lafortune
Nice. Just one more reason I can't wait until everyone upgrades their rubylibs to the latest Ruby.
Mario