Happy singleton

I love Ruby (Well…., only the programming language, I actually hate the stone)

I don’t know what makes this programming language special to me, but I would like to share a small ahh moment i had while reading about ruby

We are all familiar with the standard GOF implementation for singleton

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Logger
  def initialize
    @log = File.open("log.txt", "a")
  end
 
  @@instance = Logger.new
 
  def self.instance
    return @@instance
  end
 
  def log(msg)
    @log.puts(msg)
  end
 
  private_class_method :new
end

That’s is the plain old singleton but with some Ruby magic it can be like this

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Logger
  def initialize
    @log = File.open("log.txt", "a")
  end
 
  @@instance = Logger.new
 
  def self.instance
    return @@instance
  end
 
  def log(msg)
    @log.puts(msg)
  end
 
  private_class_method :new
end

It is some of these small things that brings me closer to Ruby every day