Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to identify aliased methods in Ruby?

Tags:

alias

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

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

like image 942
Mario Avatar asked Sep 09 '10 13:09

Mario


People also ask

How to alias method Ruby?

To alias a method or variable name in Ruby is to create a second name for the method or variable. Aliasing can be used either to provide more expressive options to the programmer using the class or to help override methods and change the behavior of the class or object.

What does Alias_method do Ruby?

The alias_method method Then the username alias is aliased with a name alias. So, a call to name , username or fullname returns the same result. We can see that the alias_method method takes a String or a Symbol as argument that allows Ruby to identify the alias and the method to alias.


1 Answers

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

like image 190
Marc-André Lafortune Avatar answered Sep 22 '22 17:09

Marc-André Lafortune