1

I want to get in difference of implementation singleton pattern in ruby vs class and vs module.I'm talking about singleton with class methods only and no instances. As for me, it is logical to use

module Foo
  def self.foo= other
    @@foo=other
  end
  def self.foo
    @@foo
  end
end

but very often I see in others code class Foo;....;end and I want to understand why?If there is no instances and no sub classes Module is more convenient. Or may be I miss something?

The question is what is the diff between module and class in singleton pattern implementation?

Mike Belyakov
  • 1,355
  • 1
  • 13
  • 24
  • Actually, there are many ways to implement Singletons in Ruby. I found the following article quite enlightening: https://www.practicingruby.com/articles/ruby-and-the-singleton-pattern-dont-get-along – user1934428 Jun 08 '16 at 05:58

2 Answers2

3

The simplest way to get an object in Ruby is to use, well, an object:

class << Foo = Object.new
  attr_accessor :foo
end

Using either a module or a class is overkill, both have features you don't need.

Jörg W Mittag
  • 363,080
  • 75
  • 446
  • 653
0

Singletons are objects whose class ensures that it is instantiated only once, and same instance is shared by all clients.

Ruby's Singleton module helps in achieving this in convenient manner.

Community
  • 1
  • 1
Wand Maker
  • 18,476
  • 8
  • 53
  • 87
  • I know what is singleton. I asked not about singleton like a stdlib module, i'm asking about singleton like programming pattern in ruby. with using module, instead of class. Yes, module can not be instantiated, but it can store own module variables, and it is with out for realize singleton pattern – Mike Belyakov Jun 08 '16 at 18:59