How to Write a Singleton Class in Ruby

A Singleton is a Design Pattern which is used to prevent a class from being instantiated more than once. So there can only be one object of that particular type of class.

Writing a Singleton Class in Ruby is very easy and much more straight forward than doing it in Java, for example.

It uses Ruby Mixins to prevent you from instantiating the same class more than once and allows you to get back the only instance which can ever be instantiated.

Of course you need to add your own methods, but here’s the minimum set up.

require 'singleton'
class TestSingleton
  include Singleton
end
a = TestSingleton.instance
irb(main):006:0> a = TestSingleton.new
NoMethodError: private method `new' called for TestSingleton:Class
	from (irb):6
VN:F [1.9.22_1171]
Rating: 0.0/5 (0 votes cast)
VN:F [1.9.22_1171]
Rating: +1 (from 1 vote)
Facebook Twitter Email

Leave a Reply