Have you ever wanted to pass a method to a function that only takes a block? Or figure out which of your object’s superclasses broke the method you’re trying to call?
Those things are easy to do with the method
method. Use it well, and you can learn about your dependencies, save yourself hours of debugging, and get your code to the places it needs to be.
Methods as easy as lambdas
Lots of Ruby methods take blocks or lambdas. But you can’t directly pass a method to another method, the way you would with a lambda. You have to use method
first:
So, what’s happening here?
The first line turns the method Math.sin
into a Method
object. Just like lambdas, `Method` objects respond to `call`. Method
objects respond to to_proc
(Thanks, Benoit). So they can be used in the same places you’d use a lambda:
Take a look at the first line again. This code, using a lambda, works the same way as the earlier code, using method
.
Depending on how you’ve written your code, getting ahold of a Method
object can be a lot easier than wrapping it in a lambda. So when you need a lambda and all you have is a method, remember the method
method.
Where did that method come from?
You just called a method on your object, and it does something you didn’t expect. Maybe someone overrode it or monkey-patched it. How do you figure this out?
You could dig through the source code for a few hours. But Method
has two methods that can speed things up.
To figure out which class defined the method you’re calling, use owner
:
When you want to go a little deeper and figure out exactly where the method was defined, use source_location
:
source_location
returns an array. The first element is the path to the file where the method was defined, and the second element is the line number. With those, you know exactly where to look next.
Reading the source (without having to dig)
Once you can figure out where a method was defined, you might want to see how it’s defined.
Method
can’t do that by itself. But if you install the method_source
gem, you can see the source code for many methods right from your console:
You can even see the comments:
Pretty awesome, right? Your documentation is right in the console!
Introspection is awesome
Some of my favorite Ruby classes are those that let you inspect your code from within your code. Classes like Class
, Module
, and Method
. With these, you can learn a ton about your code as it runs, and modify it on the fly. Learn these classes well, study their API, and you’ll be able to do amazing things with Ruby.