New allocate and initialize
suggest changeIn many languages, new instances of a class are created with a special new keyword. In Ruby, new is not a keyword. It is a class method. The definition is roughly this:
class MyClass
def self.new(*args)
obj = allocate
obj.send(:initialize, *args) # initialize is private
obj
end
end
allocate creates an uninitialized instance of the class.
Note also that the return value of initialize is discarded, and obj is returned instead. This makes it immediately clear why you can code your initialize method without worrying about returning self at the end.
The ‘normal’ new method that all classes get from Class works as above, but it’s possible to redefine it however you like, or to define alternatives that work differently. For example:
class MyClass
def self.extraNew(*args)
obj = allocate
obj.pre_initialize(:foo)
obj.send(:initialize, *args)
obj.post_initialize(:bar)
obj
end
end
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents