Last active
December 23, 2015 06:39
-
-
Save jtigger/6595108 to your computer and use it in GitHub Desktop.
Example of overriding the constructor.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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