DEV Community

[Comment from a deleted post]
Collapse
 
sudiukil profile image
Quentin Sonrel

Ruby/Rails developer here, as often in Ruby, you have to read it "in english" to understand what it does: or equals.

So @user ||= User.first reads "@user OR equals User.first", which means "Take @user value (if defined) OR (if not) make @user equal to (as in 'taking the value of') User.first (and then take the new @user value)".

You could code it this way too:

if not @user.nil
  return @user
else
  @user = User.first
  return @user
end
Collapse
 
thorstenhirsch profile image
Thorsten Hirsch

Ruby does not have an "defined-or" operator! The ||= evaluates the right side even when the left side is defined and false. Example:

irb(main):001:0> foo = false
=> false
irb(main):002:0> foo
=> false
irb(main):003:0> foo ||= true
=> true
irb(main):004:0> foo
=> true