7

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

k107
  • 15,882
  • 11
  • 61
  • 59
pachun
  • 926
  • 2
  • 10
  • 26

2 Answers2

18

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
a14m
  • 7,808
  • 8
  • 50
  • 67
Koraktor
  • 41,357
  • 10
  • 69
  • 99
  • I should have said I don't have access to standard libs because it's [rubymotion](http://rubymotion.com/). But the second method worked, so thank you very much. – pachun May 24 '12 at 20:24
  • I can't believe RubyMotion comes without support for the standard libraries. There's limited support for gems, but Ruby without the standard libraries isn't that exciting as an alternative for Obj-C: No sockets, no JSON, no …? – Koraktor May 25 '12 at 05:01
  • Apple does a lot of this: Plenty of socket libs (AFNetworking CFSocket), NSJSONSerialization, etc. And people are beginning to package all these apple provided libs in a more ruby-like syntax. Look up "ruby motion bubblewrap" – pachun Jun 11 '12 at 16:05
  • 3
    How do you initialize instance variables when using the standard Singleton module? – Dor May 27 '15 at 18:12
6

Rubymotion (1.24+) now seems to support using GCD for singleton creation

class MyClass
  def self.instance
    Dispatch.once { @instance ||= new }
    @instance
  end
end
k107
  • 15,882
  • 11
  • 61
  • 59