Skip to content

Instantly share code, notes, and snippets.

@xpepper
Last active December 17, 2015 00:59
Show Gist options
  • Save xpepper/5524811 to your computer and use it in GitHub Desktop.
Save xpepper/5524811 to your computer and use it in GitHub Desktop.
#
# A hand-rolled singleton behaviour
#
class SnowFlake
class << self
private :new
end
def self.instance
@instance ||= new
end
end
p SnowFlake.instance # => #<SnowFlake:0x1003adfd8>
p SnowFlake.instance # => #<SnowFlake:0x1003adfd8>
p SnowFlake.new
# => NoMethodError: private method ‘new’ called for SnowFlake:Class
#
# Singleton module from Ruby's standard lib
#
require 'singleton'
class SnowFlake
include Singleton
end
p SnowFlake.instance # => #<SnowFlake:0x1003adff8>
p SnowFlake.instance # => #<SnowFlake:0x1003adff8>
p SnowFlake.new
# => NoMethodError: private method ‘new’ called for SnowFlake:Class
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment