Looking for Ruby on Rails development company?
Contact Us

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
How and when to use singleton in ruby | Inkoop Blog

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


Looking for Ruby on Rails development company?
Contact Us

Related Services.



Hire ReactJS Developers
Hire Gatsby Developers
Hire NextJS Developers

We support the Open Source community.



Have a Project in mind?