Ruby Q & A

 

How do I use ‘case’ statements in Ruby?

In Ruby, the `case` statement, also known as a switch statement in other programming languages, is used to evaluate a value against a series of possible conditions and execute code based on the first matching condition. It provides a clean and efficient way to handle multiple branches of conditional logic. Here’s how to use the `case` statement in Ruby:

 

  1. Basic `case` Statement: The basic structure of a `case` statement consists of the `case` keyword, followed by the expression you want to evaluate (usually a variable), and then a series of `when` clauses that specify possible conditions. Each `when` clause contains a condition to match against the expression and a block of code to execute if the condition is true. The `else` clause is optional and serves as a fallback for when none of the conditions match.
```ruby

   grade = 'B'




   case grade

   when 'A'

     puts "Excellent!"

   when 'B'

     puts "Good job!"

   when 'C'

     puts "You passed."

   else

     puts "Needs improvement."

   end

   ```

In this example, the `case` statement evaluates the value of `grade` and executes the code block associated with the first matching condition, which is `’B’`. It will output “Good job!”

 

  1. Using Ranges: You can use ranges in `when` clauses to match values within a specific range. This is particularly useful for evaluating numeric or character ranges.
   ```ruby

   score = 85




   case score

   when 90..100

     puts "A"

   when 80..89

     puts "B"

   when 70..79

     puts "C"

   else

     puts "F"

   end

   ```

 In this example, the `case` statement uses ranges to determine the grade based on the `score`.

 

  1. Using `then` for One-Liners: You can use `then` to write one-liner code for `when` clauses when the code is short and concise.
  ```ruby

   fruit = 'apple'




   case fruit

   when 'apple' then puts "It's an apple."

   when 'banana' then puts "It's a banana."

   else puts "It's something else."

   end

   ```

The `case` statement in Ruby provides a clean and organized way to handle multiple conditions, making your code more readable and maintainable. It’s especially useful when you have a value to compare against several possible options. The `case` statement evaluates conditions sequentially and executes the first matching block of code, offering a versatile tool for branching logic in your Ruby programs.

Previously at
Flag Argentina
Chile
time icon
GMT-3
Experienced software professional with a strong focus on Ruby. Over 10 years in software development, including B2B SaaS platforms and geolocation-based apps.