Ruby Singleton Initialization

I am trying to initialize singleton in ruby. Here is the 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 initialization is never called and therefore singleton is never initialized. I tried calling initialization init, self.initialize, new and self.new. Nothing succeeded. "I initialized" was never printed, and the variable was never initialized when I instantiated

my_var = MyClass.instance

How to set up a single to initialize? Help evaluate

Pachun

+5
source share
2 answers

Rubymotion (1.24+) now supports using GCD to create singleton networks

class MyClass
  def self.instance
    Dispatch.once { @instance ||= new }
    @instance
  end
end
+6
source

:

require 'singleton'

class MyClass
  include Singleton
end

, :

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
+15

All Articles