Ways to Define Singleton Methods in Ruby

Singleton methods are methods that live in the singleton class and are only available for a single object (unlike regular instance methods that are available to all instances of the class). Singleton methods are often referred to as class methods, but that’s confusing because Ruby doesn’t have class methods. This post outlines the many different ways singleton methods can be defined.

Methods defined with dot notation are singleton methods for the receiver object.

s = 'a string'
def s.meth; end
s.singleton_methods # => [:meth]

The instance_eval() method evaluates the block in the context of the receiver, so methods defined in an instance_eval() block are singleton methods for the receiver.

x = 'moo'
x.instance_eval do
  def cow; end
x.singleton_methods # => [:cow]

Object#define_singleton_method() is the most explicit way to define singleton methods.

word = 'boo'
word.define_singleton_method(:hi) do
word.hi # => 'hey!'
word.singleton_methods # => [:hi]

Singleton methods for class objects can be added by opening the singleton class and defining the methods. After all, singleton methods are simply instance methods defined in the singleton class.

class A
  class << self # opens the singleton class
    def coolio; end
  end # closes singleton class
A.singleton_methods # => [:coolio]

Extending a class with a module adds all the methods from the module to the object’s singleton class as singleton methods.

module M
  def surf; end

class Watersport
  extend M
Watersport.singleton_methods # => [:surf]

The most common technique for adding singleton methods to classes is with dot notation (same idea as the first example):

class Fish
  def Fish.swim; end
  def self.yummy?; end
Fish.singleton_methods # => [:swim, :yummy?]

When adding singleton methods to a class, it’s better to use the self keyword instead of the class name, so if the class name changes, edits are not required in multiple places.

There are multiple techniques to create singleton methods in Ruby, but there are not any ways to make class methods because there are no class methods in Ruby. There are singleton methods for class objects that function like class methods, but it’s better to not refer to these as ‘class methods’. Get familiarized with all the different techniques to define singleton methods since all the techniques are used and it can be confusing if you don’t realize they’re all doing the same thing.


One thought on “Ways to Define Singleton Methods in Ruby

  1. Pingback: acts_as_list refactoring part 2 – Ruby clarity

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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