Ruby Singleton Methods

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

Let’s create an instance of the Person class and assign the object to the variable bob.

bob =

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"

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"
=> 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!"

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"

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"

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s