0
0
Rubyprogramming~15 mins

Conditional assignment (||=) in Ruby - Mini Project: Build & Apply

Choose your learning style9 modes available
Conditional Assignment with ||= in Ruby
📖 Scenario: You are building a simple program to track user preferences for a website. Sometimes users have not set their preferences yet, so you want to assign default values only if the preferences are missing or empty.
🎯 Goal: Learn how to use the conditional assignment operator ||= in Ruby to set default values only when variables are nil or false.
📋 What You'll Learn
Create a variable theme with the value nil
Create a variable font_size with the value nil
Create a variable language with the value "English"
Use ||= to assign "Light" to theme only if it is nil or false
Use ||= to assign 12 to font_size only if it is nil or false
Use ||= to assign "English" to language only if it is nil or false
Print the values of theme, font_size, and language
💡 Why This Matters
🌍 Real World
Websites and apps often need to set default settings for users who haven't chosen their preferences yet.
💼 Career
Understanding conditional assignment helps in writing clean, efficient Ruby code for configuration and data handling.
Progress0 / 4 steps
1
Create initial variables
Create three variables: theme set to nil, font_size set to nil, and language set to "English".
Ruby
Need a hint?

Use = to assign values to variables. nil means no value.

2
Add default values with ||= operator
Use the conditional assignment operator ||= to assign "Light" to theme, 12 to font_size, and "English" to language only if they are nil or false.
Ruby
Need a hint?

The ||= operator assigns the value only if the variable is nil or false.

3
Check the values after conditional assignment
Write a puts statement to print the values of theme, font_size, and language separated by commas.
Ruby
Need a hint?

Use puts with string interpolation to print variables separated by commas.

4
Run and see the output
Run the program and observe the output. It should print Light, 12, English.
Ruby
Need a hint?

If the output is not correct, check your variable names and the use of ||=.