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?✗ Incorrect
||= assigns the value only if the variable is nil or false, otherwise it keeps the original value.
If
score = 0, what will score ||= 10 do?✗ Incorrect
Since 0 is neither nil nor false, score ||= 10 keeps score as 0.
Which values cause
||= to assign the new value?✗ Incorrect
||= assigns the new value if the variable is either nil or false.
What is a common use of
||= in Ruby?✗ Incorrect
||= is often used to set default values if a variable is not already set.
What will this code print?<br>
flag = false flag ||= true puts flag
✗ Incorrect
Since flag is false, flag ||= true assigns true to flag.
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.