Understanding allocate

Understanding allocate

In rare circumstances you might want to create an object without calling its constructor (bypassing initialize). For example, maybe you have an object whose state is determined entirely by its accessors; then it isn't necessary to call mew (which calls initialize) unless you really want to. Imagine you are gathering data a piece at a time to fill in the state of an object; you might want to start with an "empty" object rather than gathering all the data up front and calling the constructor.

The allocate method was introduced in Ruby 1.8 to make this easier. It returns a "blank" object of the proper class, yet uninitialized.

class Person
attr_accessor :name, :age, :phone

def initialize(n,a,p)
@name, @age, @phone = n, a, p
end
end

p1 = Person.new("John Smith",29,"555-1234")

p2 = Person.allocate

p p1.age # 29
p p2.age # nil

你可能感兴趣的:(Ruby,UP)