Design Patterns - A Singleton in Ruby

Rusty Divine recently posted a look at the Singleton design pattern, with some Java and C# based examples.

I wanted to show that same pattern using Ruby:

require 'singleton'

class Hermit
  include Singleton

That's it.

Using Ruby's powerful Mixin functionality, we bring the singleton code into our class definition. This automatically makes our class's new method private, and give us an instance method we can use to get our object:

irb(main):005:0> a =
NoMethodError: private method `new' called for Hermit:Class
        from (irb):5
irb(main):006:0> a = Hermit.instance
=> #<Hermit:0x20a1cc>

That was easy, wasn't it?