0
0
Rubyprogramming~5 mins

Conditional assignment (||=) in Ruby

Choose your learning style9 modes available
Introduction

Conditional assignment helps you set a value only if the variable is nil or false. It keeps your code simple and avoids overwriting existing values.

When you want to give a variable a default value only if it doesn't have one yet.
When you want to avoid changing a variable that already has a useful value.
When you want to simplify code that checks if a variable is nil or false before assigning.
When you want to set configuration options only if they are not already set.
Syntax
Ruby
variable ||= value

This means: assign value to variable only if variable is nil or false.

It is a shortcut for variable = variable || value.

Examples
If name is nil or false, it becomes "Guest". Otherwise, it keeps its current value.
Ruby
name ||= "Guest"
If count is nil or false, it becomes 0.
Ruby
count ||= 0
Sets the theme to "light" only if settings[:theme] is nil or false.
Ruby
settings[:theme] ||= "light"
Sample Program

First, name is nil, so it gets assigned "Alice". Then, since name already has "Alice", it does not change to "Bob".

Ruby
name = nil
name ||= "Alice"
puts name

name ||= "Bob"
puts name
OutputSuccess
Important Notes

Remember, ||= only assigns if the variable is nil or false. If the variable has any other value, it stays unchanged.

This operator is very useful for setting default values in a clean way.

Summary

Conditional assignment (||=) sets a variable only if it is nil or false.

It helps keep existing values and only fills in defaults when needed.

Use it to write shorter and clearer code for default values.