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)".
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:
Ruby does not have an "defined-or" operator! The
||=
evaluates the right side even when the left side is defined and false. Example: