<< ThreadJoin | Index | << >>
a ||= 123
can be replaced to
if a == nil a = 123 end
Basically, it would be better to understand the followings:
true || true => true true || false => true false || true => true false || false => false
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.
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.