What is the correct way to write a switch statement in Ruby?
How can I implement a case when statement in Ruby to handle multiple conditions efficiently? What is the best practice for using the case when in Ruby syntax?
What is the correct way to write a switch statement in Ruby?
How can I implement a case when statement in Ruby to handle multiple conditions efficiently? What is the best practice for using the case when in Ruby syntax?
Basic case when Syntax : The case when statement in Ruby is similar to a switch statement in other languages like JavaScript or C. Here’s a basic example:
value = 2
case value
when 1
puts "One"
when 2
puts "Two"
when 3
puts "Three"
else
puts "Not in range"
end
This checks value against multiple conditions and executes the corresponding block. The else acts like a default case.
That’s a great starting point, but Ruby’s case when is even more powerful. You can use ranges and multiple values per condition:
score = 85
case score
when 90..100
puts "Grade: A"
when 80..89
puts "Grade: B"
when 70..79
puts "Grade: C"
else
puts "Needs Improvement"
end
This is great for checking number ranges without complex conditionals. You can also check against multiple values in a single when:
fruit = "apple"
case fruit
when "apple", "banana", "mango"
puts "This is a fruit"
when "carrot", "broccoli"
puts "This is a vegetable"
else
puts "Unknown item"
end
Both are solid approaches, but here’s something cool—case can work like a series of if statements when no variable is provided:
age = 25
case
when age < 18
puts "You're a minor"
when age >= 18 && age < 65
puts "You're an adult"
else
puts "You're a senior citizen"
end
This is useful when you need condition-based logic rather than direct comparisons.