Skip to content

Instantly share code, notes, and snippets.

@zdavatz
Created March 17, 2011 12:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zdavatz/874252 to your computer and use it in GitHub Desktop.
Save zdavatz/874252 to your computer and use it in GitHub Desktop.
persistable.rb
@zdavatz
Copy link
Author

zdavatz commented Mar 17, 2011

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

  1. 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

  1. 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.

@zdavatz
Copy link
Author

zdavatz commented Mar 17, 2011

def odba_observers
@odba_observers ||= []
end

can be replace to

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment