Possible Duplicate:
What does ||= mean in Ruby?
开发者_StackOverflow中文版 class Person
attr_accessor :name
class << self
attr_accessor :instances
def instances
@instances ||= []
@instances
end
end
def initialize( name )
Person.instances << self
@name = name
end
end
joe = Person.new( "Joe" )
zach = Person.new( "Zach" )
puts "You have #{Person.instances.size} people in existance!" POINT C
class Paramedic < Person
def initialize( name )
super( name )
Paramedic.instances << self
end
end
sally = Paramedic.new( "Sally" )
puts "You have #{Person.instances.size} people in existance!" #POINT B
puts "You have #{Paramedic.instances.size} paramedics in existance!" POINT C
What do these lines do?
@instances ||= []
Person.instances << self
Paramedic.instances << self
There is class level variable @instances.
First line
@instances ||= []
initialise this variable by empty array if @instances is nil.
Then during initialisation of instance of class Person code Person.instances << self add this instance to array of all instances of class Person.
So if you call Person.instances you will give all instances of class Person.
Same situation with Paramedic.
This code essentially keeps track of instances of Person and Paramedic. Each time one of these is constructed, the created object is added to the list represented by the class variable instances. self refers to the instance itself in this case.
@instances ||= [] is a Ruby idiom that is short for @instances = @instances || []. Because in Ruby only false and nil evaluate to false, the snippet either returns @instances or an empty list if @instances does not yet exist.
加载中,请稍侯......
精彩评论