Listing and Chaining Methods

Learn how to find the methods defined for an object and how to call multiple methods on a single line of code.

We'll cover the following

Listing methods

As mentioned before, if you’re curious what methods are defined on a certain object, then you can check the Ruby documentation for the class. Usually, the right page conveniently shows up at the top when you search for “ruby” and the class name.

However, we can also quickly ask the object for its methods. That’s right, methods is a method defined on all objects, just like class and is_a?.

When we call it, it returns (responds with) an array with all method names that the object has.

It makes sense to sort the array to make it easier to read, like so:

Press + to interact
print "Ruby Monstas".methods.sort

The method names come as symbols because they’re considered code.

Chaining method calls

The code above also demonstrates that methods can be chained. When we call a method on an object, it returns another object to us. We can then immediately call another method on that new object, and so on.

In our example above, the methods method returns an array of names. An Array object has the sort method, so we can call this method immediately by using another ..

We could chain some of the methods calls from our string example earlier, like so:

Press + to interact
name = "Ruby Monstas"
puts name.prepend("Oh, hello, ").upcase

Notice that Ruby first evaluates the name.prepend("Oh, hello, "). It does this to identify the object (the new string) returned from this so that it can then call the upcase method on this new object.