0
0
Rubyprogramming~5 mins

Conditional assignment (||=) in Ruby - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does the operator ||= do in Ruby?
It assigns a value to a variable only if that variable is currently nil or false. It means "assign if not already set."
Click to reveal answer
beginner
Given name ||= "Guest", what happens if name is already "Alice"?
The value of name stays "Alice" because ||= only assigns if name is nil or false.
Click to reveal answer
beginner
Why is ||= useful in Ruby programs?
It helps set default values without overwriting existing ones, making code cleaner and easier to read.
Click to reveal answer
intermediate
What will be the output of this Ruby code?<br>
count = nil
count ||= 10
count ||= 20
puts count
The output will be 10. The first ||= assigns 10 because count is nil. The second ||= does nothing because count is already 10 (not nil or false).
Click to reveal answer
intermediate
Can ||= assign a value if the variable is false?
Yes. ||= treats both nil and false as "not set" and will assign the new value in either case.
Click to reveal answer
What does variable ||= value do in Ruby?
AAssigns value only if variable is nil or false
BAlways assigns value to variable
CAssigns value only if variable is true
DAssigns value only if variable is a number
If score = 0, what will score ||= 10 do?
AAssign 10 to score
BRaise an error
CKeep score as 0
DAssign nil to score
Which values cause ||= to assign the new value?
AOnly nil
BBoth nil and false
CAny value
DOnly false
What is a common use of ||= in Ruby?
ATo set default values
BTo multiply numbers
CTo delete variables
DTo compare strings
What will this code print?<br>
flag = false
flag ||= true
puts flag
Afalse
Bnil
Cerror
Dtrue
Explain how the ||= operator works in Ruby and give a simple example.
Think about setting a variable only if it doesn't have a useful value yet.
You got /3 concepts.
    Describe a situation where using ||= can make your Ruby code cleaner.
    Consider when you want to assign a value only if none exists.
    You got /3 concepts.