How and when to use singleton in ruby | Inkoop Blog

Singleton is a class which can have only one instance. We talk about how and when to use that in Ruby to make your code better.

Posted by Ameena on 15 Mar 2018

If you are landing to this page, I assume that you will be knowing the concept of singleton, that is straightforward: only a single instance of a class can exist.

In Ruby, a singleton class is something implicit to every Object. It's always there, you can make use of it whenever you need.

How to use singleton class


require 'singleton'

class Person

  include Singleton
  attr_accessor :name

  def details
    puts name


This will give us

test.rb:14:in `<main>': private method `new' called for Person:Class (NoMethodError)

Which makes sense, the whole point of using singleton class is to no longer create an instance of the Person class in an ordinary way.

To access instance of this class, we need to use the instance() method provided by the Singleton module.

You can confirm if using singleton actually gives us one instance of the class


person1, person2 = Person.instance, Person.instance
puts person1 == person2

which will give you true.

Duplicating the singleton instance and changing name value will end up giving you the latest updated value as below:


... = "Ameena"

person = Person.instance = "Shad"


Gives you Shad.

keep Coding !!!


Have a Project in mind?