0
0
Rubyprogramming~20 mins

Conditional assignment (||=) in Ruby - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Ruby Conditional Assignment Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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
A0
Bnil
CError
D10
Attempts:
2 left
💡 Hint
Remember ||= assigns the value only if the variable is nil or false.
Predict Output
intermediate
2: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
Anil
B10
C5
DError
Attempts:
2 left
💡 Hint
The ||= operator does not overwrite if the variable is already truthy.
🔧 Debug
advanced
2: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
AThe code runs fine and returns 10
BThe code raises a SyntaxError due to misplaced ||= operator
CThe second ||= is ignored because @var is nil
DUsing ||= on an uninitialized instance variable causes a NameError
Attempts:
2 left
💡 Hint
Instance variables default to nil if uninitialized.
🧠 Conceptual
advanced
2:00remaining
What does ||= do in Ruby?
Choose the best description of what the ||= operator does in Ruby.
AAssigns the right value only if the left variable is nil or false
BAlways assigns the right value to the left variable
CAssigns the right value only if the left variable is truthy
DAssigns the right value only if the left variable is zero
Attempts:
2 left
💡 Hint
Think about when ||= skips assignment.
Predict Output
expert
2: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
A100
BError
Cnil
Dfalse
Attempts:
2 left
💡 Hint
Consider operator precedence and what ||= applies to here.