views:

121

answers:

3

In java I would create something like this:

private static MyClass instance;

public static MyClass getInstance() {
  if(instance != null) {
    return instance;
  }
  instance = new MyClass();
  return instance;
}

What is the appropriate way to obtain the same functionality in ruby?

Update: I've read about 'include Singleton' but when I tried to do it in irb on Ruby 1.9 I got:

[vertis@raven:~/workspace/test]$ ruby -v
ruby 1.9.1p378 (2010-01-10 revision 26273) [i386-darwin9.4.0]
[vertis@raven:~/workspace/test]$ irb
irb(main):001:0> class TestTest
irb(main):002:1>   include Singleton
irb(main):003:1> end
NameError: uninitialized constant TestTest::Singleton
    from (irb):2:in `<class:TestTest>'
    from (irb):1
    from /usr/local/bin/irb:12:in `<main>'
+5  A: 

In general, this pattern is called a Singleton.

The following page should help you get this functionality in ruby: http://ruby-doc.org/stdlib/libdoc/singleton/rdoc/index.html

ar
Tried this and it doesn't appear to exist in ruby 1.9, has this been changed?
Vertis
Apparently you have to require 'singleton' first...Nevermind then
Vertis
A: 

This is called singleton pattern. You can check it out here:

http://www.rubyist.net/~slagell/ruby/singletonmethods.html

http://dalibornasevic.com/posts/9-ruby-singleton-pattern-again

anthares
+4  A: 

there are already answers to how to do it in Ruby, but I'd ask first do you need to?

There is no need to copy your Java patterns to Ruby. I'm doing Ruby from 2005 and never did I need a singleton class.

Why do you need an instance to begin with? Why can't you just define class methods and call them on the class.

As I understand you are trying smth like:

instance = Klass.new
instance.foo
.. then somewhere else
instance = Klass.new # expecting this to return the same instance
instance.bar

But instead you can just do this:

Klass.foo
... in other place
Klass.bar

And since thre is only one class Klass your problem is natively solved and with less to type too :)

classes in Ruby are just instances of class Class, so they can have everything an instance can have.

Vitaly Kushner
I love this idea. Is the Singleton mixin ever actually needed, I wonder?
Shadowfirebird
Vertis