11

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?

1
  • This question received a close vote as "too broad," but it's not: it has an obvious and succinct answer in Ruby. Jul 11, 2015 at 11:50

3 Answers 3

10

Actually, the above answer was not completely correct.

require 'singleton'

class Example
  include Singleton
end

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

8

Use the singleton module:

class Clazz
  include Singleton
end

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

0

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 !).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.