Playing with methods
Posted by Sandro Paganotti in
Ruby on Rails -
1 comment
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 time to play with 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 introspection 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), getting the vanilla ‘length’ method that you can next ‘bind’ to a new variable.
len_unbinded = len.unbind
new_txt = "haloa!"
new_len = len_unbinded.bind(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 class that can be found on the Method class RDoc, so if you are interested in this topic, or just curious, please have a look.


Comments
Anil Wadghule
Posted on April 27