4.1. Defining Methods

Every object and class exposes several methods. Class methods are methods that can be invoked directly on classes, for example ActiveRecord's finders:

author = Author.find_by_last_name("Ginsberg")

Similarly, there are instance methods that can be invoked on any object of a given class, like the downcase method of a String, or to keep in line with ActiveRecord's example:

books = author.books

Then there are the so-called singleton methods, which are a special type of method that can be defined, and which exist only for a specific instance of a class:

my_string.my_method    # my_string has a singleton method
my_string2.my_method   # Raises a NoMethodError

Ruby doesn't really differentiate between the three of them when you call a given method on a class or an object. The interpreter only cares about determining whether or not the receiver exposes that method. When you use the syntax receiver.method, Ruby is actually sending a message with the name of the method, and its arguments, to the receiver object (be it an object, class, or module). As a matter of fact, the following two are equivalent, and the dot notation is just sugar syntax for the developer:

"antonio".capitalize          # "Antonio"
"antonio".send(:capitalize)   # "Antonio"

You can see the advantages of the dot notation when chaining multiple method calls together as shown here:

puts "$32.90".sub('$','Đ')                          # Prints Đ32.90
Kernel.send(:puts, "$32.90".send(:sub, '$', 'Đ'))   # Prints Đ32.90

As a reminder, the values ...

Get Ruby on Rails® for Microsoft Developers now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.