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中allocate方法的使用场景,该方法允许创建未初始化的对象实例,这对于某些特定情况非常有用,例如当对象的状态完全由其访问器确定时。

1053

被折叠的 条评论
为什么被折叠?



