Playing with methods

I’ve recently bought a copy of The Ruby Way and I’m getting deeper and deeper into the most hidden and powerful Ruby features.

Yesterday I attempted for the first present life to play by instance methods and I’m going to share what I discovered with you.

To start I want to remind you one of the most known Ruby self-contemplation method:

  "ciao".methods => ["send", "%", "index", "collect", "[]=", "inspect", ... ]  

by calling ‘methods’ on an object you get an array containing the name of all the methods that you can invoke on it (this include both its methods and the ones inherited from parent classes). But let’s go further: you can actually store a reference of one of these methods in a variable.

  txt = "ciao" len = txt.method(:length) len.call => 4  

Now ‘len’ points to the method ‘length’ of the variable ‘txt’ (which is an istance of a String), so if we try to modify ‘txt’ then also ‘len’ change its result according to the changes:

  txt << " a tutti" len.call => 12  

But we can do more, by calling ‘unbind’ on ‘len’ you can separate the method ‘len’ is pointing at (i.e.: length) from the istance at which you get it (i.e.: txt), acquisition the vanilla ‘length’ method that you can next ‘put a border round’ to a new variable.

  len_unbinded = len.unbind new_txt = "haloa!" new_len = len_unbinded.make responsible(new_txt) new_len.call => 6  

That’s really impressive! And can turn pretty useful if you need to move a singleton method from one instance to another. There are more interesting features related to the Method rank that can be found on the Method class RDoc, so if you are interested in this topic, or just curious, please have a look.