Challenge - 5 Problems
Ruby Conditional Assignment Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
What is the output of this Ruby code using ||= operator?
Consider the following Ruby code snippet. What will be printed when it runs?
Ruby
value = nil value ||= 10 puts value
Attempts:
2 left
💡 Hint
Remember ||= assigns the value only if the variable is nil or false.
✗ Incorrect
The ||= operator assigns the right side value only if the left side is nil or false. Since value starts as nil, it gets assigned 10.
❓ Predict Output
intermediate2:00remaining
What will be the value of variable after conditional assignment?
What is the value of
count after this code runs?Ruby
count = 5 count ||= 10 puts count
Attempts:
2 left
💡 Hint
The ||= operator does not overwrite if the variable is already truthy.
✗ Incorrect
Since count is already 5 (which is truthy), count ||= 10 does not change it.
🔧 Debug
advanced2:00remaining
Why does this code raise an error with ||= operator?
This Ruby code raises an error. Which option explains the cause?
Ruby
def example @var ||= 5 @var = nil @var ||= 10 end example
Attempts:
2 left
💡 Hint
Instance variables default to nil if uninitialized.
✗ Incorrect
Instance variables in Ruby default to nil if not set. The first ||= assigns 5, then @var is set to nil, so the second ||= assigns 10. The code runs fine and returns 10.
🧠 Conceptual
advanced2:00remaining
What does ||= do in Ruby?
Choose the best description of what the ||= operator does in Ruby.
Attempts:
2 left
💡 Hint
Think about when ||= skips assignment.
✗ Incorrect
The ||= operator assigns the right side value only if the left side is nil or false (i.e., falsy). Otherwise, it keeps the original value.
❓ Predict Output
expert2:00remaining
What is the output of this Ruby code with ||= and method calls?
What will this Ruby code print?
Ruby
def get_value nil end result = get_value ||= 100 puts result
Attempts:
2 left
💡 Hint
Consider operator precedence and what ||= applies to here.
✗ Incorrect
The expression get_value ||= 100 tries to assign to the method get_value, which is not allowed. This causes a SyntaxError.