O'Reilly logo

Ruby on Rails® for Microsoft Developers by Antonio Cangiano

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required