Member-only story

Ruby Singleton Pattern to Read File Content From Various Type of File

Gokul
2 min readSep 5, 2020

--

What is a Singleton Pattern?

Singleton is one of the innovative design patterns that support only one instance will be available globally to use

How to define Singleton class in ruby?

require 'singleton'class BoroKlass
include Singleton
end

How to instantiate the BoroKlass?

In ruby we use BoroKlass.new to create the class instance right? Let’s try the same here!!!

Ohhhh noooo… BoroKlass.new returns the following error:

NoMethodError (private method `new’ called for BoroKlass:Class)

Then how to do that? It’s very simple just type BoroKlass.instance this gives the new BoroKlass object.

#<BoroKlass:0x00007f89efe6fca0>

It’s cool right???

How to verify singleton using the same object or not?

Here is the way, first create the two variable as follows:

instance_one = BoroKlass.instance
instance_two = BoroKlass.instance

Then try the following two lines to view the object id

instance_one.object_id    # 70115206069840
instance_two.object_id # 70115206069840

--

--

Gokul
Gokul

No responses yet