0
0
Rubyprogramming~5 mins

Case/when statement in Ruby - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a case/when statement in Ruby?
It is a control structure that lets you compare a value against multiple conditions and execute code based on the first matching condition.
Click to reveal answer
beginner
How do you write a simple case/when statement in Ruby?
Use case followed by the value, then multiple when clauses for conditions, and else for default. Example:<br>
case x
when 1
  puts "One"
when 2
  puts "Two"
else
  puts "Other"
end
Click to reveal answer
intermediate
Can a when clause check multiple values at once?
Yes! You can separate values with commas to check if the case value matches any of them. Example:<br>
case x
when 1, 3, 5
  puts "Odd number"
end
Click to reveal answer
intermediate
What happens if no when condition matches and there is no else clause?
The case statement returns nil and no code inside the when blocks runs.
Click to reveal answer
intermediate
How is case/when different from multiple if/elsif statements?
Both control flow choices check conditions, but case/when is cleaner when comparing one value against many options, making code easier to read.
Click to reveal answer
What keyword starts a case statement in Ruby?
Awhen
Bcase
Cif
Dswitch
How do you specify multiple values in a single when clause?
AUse parentheses
BUse multiple <code>when</code> lines
CUse semicolons
DSeparate values with commas
What does the else clause do in a case statement?
ARuns if no <code>when</code> matches
BRuns before any <code>when</code>
CEnds the case statement
DIs required for case to work
What value does a case statement return if no conditions match and no else is given?
A0
Bfalse
Cnil
DAn error
Which is a benefit of using case/when over multiple if/elsif?
ACleaner code when checking one value against many options
BRuns faster always
CAllows complex boolean expressions
DRequires less typing for all conditions
Explain how a case/when statement works in Ruby and give a simple example.
Think about how you check one value against many choices.
You got /4 concepts.
    Describe how you can check multiple values in a single when clause and why that might be useful.
    Imagine you want to run the same code for several possible values.
    You got /3 concepts.