DISABLE ADBLOCK

ADBlock is blocking some content on the site

ADBlock errore

How do I create a Class using the Singleton Design Pattern in Ruby?

StackOverflow https://stackoverflow.com/questions/4677

Question

The singleton pattern is a design pattern that is used to restrict instantiation of a class to one object instance. Although I know how to code the singleton pattern in C++ and Java, I was wondering if anyone know how to implement it in Ruby?

Solution

Actually, the above answer was not completely correct.

require 'singleton'

class Example
  include Singleton
end

You also need to include the require 'singleton' statement.

OTHER TIPS

Use the singleton module:

class Clazz
  include Singleton
end

See http://www.ruby-doc.org/stdlib/libdoc/singleton/rdoc/index.html for more info.

You could use modules to the same effect I believe, although its not "the singleton pattern" you can have global state that way (which is what a singleton is ! Naughty global state !).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow