Code Editor
We've seen that we can use the =
operator to assign a value to a variable. But what if we only want to assign a variable if it hasn't already been assigned?
For this, we can use the conditional assignment operator: ||=
. It's made up of the or (||
) logical operator and the normal =
assignment operator.
Run the code in the editor. Here's what's happening:
favorite_book
is set to nil
, which is Ruby for "nothing." When you try to puts
it to the screen, you get exactly that: nothing!favorite_book
to "Why's (Poignant) Guide to Ruby," which it gladly does.