0

Possible Duplicate:
What does ||= mean in Ruby?

  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
Community
  • 1
  • 1
newcomer
  • 81
  • 3
  • 6

2 Answers2

2

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.

petRUShka
  • 9,812
  • 12
  • 61
  • 95
  • Why is || used ? why not @instances = [] – newcomer Jul 25 '11 at 11:09
  • Because that would reset @instances every time `instances` accessor is called. In other words calling `Person.instances` would always return `[]` – Mchl Jul 25 '11 at 11:17
  • If you don't use || you will get [] at the start of all initialisations – petRUShka Jul 25 '11 at 11:17
  • Because doing that would always assign `@instances` with an empty array. As already explained in the answers, `||=` assigns the right side only if left side is `nil`. Note that `@instances` is part of _class_ `Person`, *not* part of instance of `Person`. – merryprankster Jul 25 '11 at 11:18
0

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.

martido
  • 373
  • 2
  • 9