How and when to use singleton in ruby

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


#singleton_test.rb

require 'singleton'

class Person

  include Singleton
  attr_accessor :name

  def details
    puts name
  end

end

Person.new

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


#singleton_test.rb

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


#singleton_test.rb

...
Person.instance.name = "Ameena"

person = Person.instance
person.name = "Shad"

Person.instance.details

Gives you Shad.

keep Coding !!!

Ameena



What do we do?


We work on website development using Ruby on Rails, NodeJS, ReactJS, AngularJS. View all the services we provide here.


Say Hello! See our work