initializing ruby singleton

pachun picture pachun · May 24, 2012 · Viewed 12.8k times · Source

I'm trying to initializing a singleton in ruby. Here's some code:

class MyClass
  attr_accessor :var_i_want_to_init

  # singleton
  @@instance = MyClass.new
  def self.instance
    @@instance
  end

  def initialize # tried 1. initialize, 2. new, 3. self.initialize, 4. self.new
    puts "I'm being initialized!"
    @var_i_want_to_init = 2
  end
end

The problem is that initialize is never called and thus the singleton never initialized. I tried naming the init method initialize, self.initialize, new, and self.new. Nothing worked. "I'm being initialized" was never printed and the variable never initialized when I instantiated with

my_var = MyClass.instance

How can I setup the singleton so that it gets initialized? Help appreciated,

Pachun

Answer

Koraktor picture Koraktor · May 24, 2012

There's a standard library for singletons:

require 'singleton'

class MyClass
  include Singleton
end

To fix your code you could use the following:

class MyClass
  attr_accessor :var_i_want_to_init

  def self.instance
    @@instance ||= new
  end

  def initialize # tried 1. initialize, 2. new, 3. self.initialize, 4. self.new
    puts "I'm being initialized!"
    @var_i_want_to_init = 2
  end
end