Ruby objects can acquire methods that are not defined in the class (these are called singleton methods), and this feature is not available in all other object oriented programming languages.
Let’s define a basic Person class:
class Person end
Let’s create an instance of the Person class and assign the object to the variable bob.
bob = Person.new
Add a funny method to the bob object that returns the string “I am bob and my name rhymes with lob”.
def bob.funny "I am bob and my name rhymes with lob" end
The bob object now has a funny method, but other instances of the Person class do not have funny methods.
>> bob.funny => "I am bob and my name rhymes with lob" >> Person.new.funny => NoMethodError exception
Singleton methods are available to a certain object, but not available to other objects of the class. Here is another syntax to open add a singleton method to the bob object:
class << bob def say_my_name "I am BOB!" end end
The Ruby programming language only has instance methods, so “class methods” are really just singleton methods on the class. In the following example, the about method is a singleton method of the Animal class. Everything is an object in Ruby, including the Animal class itself, but that is a discussion for another post.
class Animal def self.about "We are living creatures" end end
The singleton_methods method can be used to demonstrate that about is a singleton method for the Animal class.
>> Animal.singleton_methods => [:about]
The alternate singleton method definition syntax can also be used to define “class” methods in Ruby:
class Animal class << self def heartbeat "Yup, we have hearts that beat" end end end