Skip to content

Instantly share code, notes, and snippets.

@jtigger
Last active December 23, 2015 06:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jtigger/6595108 to your computer and use it in GitHub Desktop.
Save jtigger/6595108 to your computer and use it in GitHub Desktop.
Example of overriding the constructor.
class Foo
@@cache = {}
def initialize(id)
puts "initialize"
@id = id
end
def Foo.new(id)
if @@cache[id]
puts "cache hit."
else
puts "cache miss."
@@cache[id] = super # calls Object.new with original parameters, which in turn calls initialize.
end
@@cache[id]
end
def id
@id
end
end
x = Foo.new(1)
y = Foo.new(1)
puts "X = #{x.id}; Y = #{y.id}"
puts x === y
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment