view · edit · sidebar · attach · print · history

The meaning of ||= []

<< ThreadJoin | Index | << >>

  a ||= 123

can be replaced to

 if a == nil
   a = 123
 end

Basically, it would be better to understand the followings:

  • 1. every value in Ruby other than 'nil' and 'false' is recognized as 'true'
  • 2. '||' (or operation) is as follows

true || true => true true || false => true false || true => true false || false => false

  • 3. If the left statement of '||' above becomes 'true' then the left

statement does not run

For example,

 a = false
 a || print 'hello'  #=> 'hello' is shown

 a = true
 a || print 'hello' #=> 'hello' is not shown

4. Namely,

a ||= 123

if 'a' equals to 'nil' or 'false, then '=123' statement runs, a = 123, otherwise, if a equals to anything other than 'nil' and 'false', a is recognized as 'true' then '=123' does not run. just 'a' runs but nothing happens, because, in Ruby, numbers and characters does not anything.

a ||= []

This is also the same.

If 'a' equals to 'nil' or 'false, then 'a = []' runs, otherwise, nothing runs. In Ruby, a variable which appears at the first time in the source code is always 'nil'.

So,

a ||= []

is usually used for the variable initialization.

a = []

is also possible for the initialization, but it might overwrite the previous value that 'a' kept.

Note

  def odba_observers
    @odba_observers ||= []
  end

can be replace to

  def odba_observers
    if @odba_observers == nil
        @odba_observers = []
    end
    return @odba_observsers
  end

Ruby method returns the value that runs at the end in the method.

view · edit · sidebar · attach · print · history
Page last modified on March 17, 2011, at 02:52 PM