Ruby: Case (aka Switch) Statements

Case Statements

Switch statements are formed using the case keyword in Ruby. Consider the following if – elsif – if statement:

# statement-1
if item_counts[item_id] === 1
  count = 1
elsif item_counts[item_id] === 2
  count = 2
else
  count = 0
end

You can achieve the same if-elsif-if logic in statement-1 above with a case statement:

# statement-2
case item_counts[item_id]
when 1
  count = 1
when 2
  count = 2
else
  count = 0
end

case uses the case-equal ( === ) operator under the hood to compare values.

Ranges in Case Statements

# statement-3
case product_scores[product_id]
when (1..3)
  score_str = "high"
when (4..7)
  score_str = "moderate"
else
  score_str = "low"
end

Regular Expressions in Case Statements