Skip to Content
Ruby on Rails® for Microsoft Developers
book

Ruby on Rails® for Microsoft Developers

by Antonio Cangiano
April 2009
Intermediate to advanced content levelIntermediate to advanced
479 pages
12h 55m
English
Wrox
Content preview from Ruby on Rails® for Microsoft Developers

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

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Ruby on Rails™ 3 Tutorial: Learn Rails™ by Example

Ruby on Rails™ 3 Tutorial: Learn Rails™ by Example

Michael Hartl

Publisher Resources

ISBN: 9780470374955Purchase book