Messages with Methods in Ruby
You hear it all the time when reading about Ruby: everything is an object. Objects in Ruby communicate with other objects by passing "messages" back and forth to one another. Well, those messages are passed by using these things called methods, and Ruby let's us easily see all the methods available on any object at any given time.
Quickie
Let's take a look at what all this means. Open up a repl:
> "goo".class
=> String
> "goo".class.superclass
=> Object
We've created a string goo
on the fly and looked up it's class
and superclass
. There's all the proof we need that we are dealing with an object. To see what methods we can call on this string object we can do:
> "goo".methods
Pretty cool. Want to look up the methods on your object's class? No problem:
> "goo".class.methods
What if you don't have an instance of a class handy and just want to see what instance methods exist for a given class?
> String.instance_methods
This list of methods includes all the methods an instance of the String class inherits. Maybe you only want the methods declared on a string?
> String.instance_methods.count
=> 188
> (String.instance_methods - Object.instance_methods).count
=> 120
Either way, that gives us a long list of methods to play with. In fact, let's try one out together right now. I see a reverse
method in there, so let's see what that does:
> "goo".reverse
=> "oog"
> "goo".reverse.upcase
=> "OOG"
Good times. What's this to_yaml
do?
> ""goo"".to_yaml
=> ""--- goo\n...\n""
Are you finding these lists of methods too difficult to sort through?
> String.instance_methods.sort
# alphabetical order
> String.instance_methods.grep /^re/
# returns instance methods that start with 're'
Ruby is pretty declarative and to the point, and playing around with methods like this quickly demonstrates that point. There is something that just feels right about writing code in order to learn more about code. It is the little things like this that can make it so enjoyable to work with.
(▰˘◡˘▰)