0
0
Rubyprogramming~20 mins

Case/when statement in Ruby - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Case/When Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of a simple case/when statement
What is the output of this Ruby code?
Ruby
value = 3
result = case value
         when 1 then "One"
         when 2 then "Two"
         when 3 then "Three"
         else "Other"
         end
puts result
ATwo
BThree
COther
DOne
Attempts:
2 left
💡 Hint
Check which 'when' matches the value 3.
Predict Output
intermediate
2:00remaining
Case statement with multiple matches
What will this Ruby code print?
Ruby
grade = 'B'
result = case grade
         when 'A', 'B' then "Pass"
         when 'C' then "Average"
         else "Fail"
         end
puts result
AAverage
BError
CFail
DPass
Attempts:
2 left
💡 Hint
Look at the first matching when clause with multiple values.
🔧 Debug
advanced
2:00remaining
Identify the error in this case/when statement
What error does this Ruby code raise?
Ruby
value = 5
case value
when 1
  puts "One"
when 5
  puts "Five"
else
  puts "Other"
end
ASyntaxError: unexpected end-of-input, expecting 'end'
BNoMethodError: undefined method 'puts' for nil:NilClass
CNo error, prints 'Five'
DRuntimeError: case expression error
Attempts:
2 left
💡 Hint
Check if all blocks and the case statement are properly closed.
Predict Output
advanced
2:00remaining
Case statement with range conditions
What is the output of this Ruby code?
Ruby
score = 75
result = case score
         when 0..59 then "Fail"
         when 60..79 then "Pass"
         when 80..100 then "Excellent"
         else "Invalid"
         end
puts result
APass
BExcellent
CFail
DInvalid
Attempts:
2 left
💡 Hint
Check which range includes 75.
🧠 Conceptual
expert
2:00remaining
Behavior of case/when with no matching condition
What will be the value of 'result' after running this Ruby code?
Ruby
value = :unknown
result = case value
         when :one then 1
         when :two then 2
         end
Anil
B0
CRaises an error
Dfalse
Attempts:
2 left
💡 Hint
What does case return if no when matches and no else is given?