Case Statement: Ruby

Case Statement: Ruby

Ruby whats good

Hello y'all, in this post I would be writing on how intuitive case statements are in Ruby. Ruby powers some popular websites in the world. And do you know that one of the languages powering GitHub is Ruby? Ok, let me not sidetrack. Let us get into the use of the case statement in Ruby.

food = gets.chomp
case food
when "plantain"
  puts "I ate plantain"
when "beans"
  puts "I ate beans"
when 'rice'
    puts "I ate rice"
end

A run-down of what the code above does

  • The gets.chomp method collects input from a user and strips off the new-line at the end of the input.
  • The case statement selects the variable that the when statement uses to compare values.
  • If any of the when statements matches the value of the food variable, it executes the code within it.
  • So let us say you input rice as food, the case statement would print "I ate rice".
  • A case statement must end with the end keyword.

The case statement above is quite limiting. What happens when a user inputs a value that isn't handled by the when statement? From the code above nothing would be logged out.

The good thing about the case statement in Ruby is that it supports the use of the else statement.

When the else statement is used within the case statement it handles all the values that aren't handled by the when statement. The example below explains further:

food = gets.chomp
case food
when "plantain"
  puts "I ate plantain"
when "beans"
  puts "I ate beans"
when 'rice'
    puts "I ate rice"
else
    puts "#{food} wasn't handled by when"
end

When a user inputs a value that isn't handled by the when statement the code within the else statement is executed.

And finally, the when statement allows you to compare a group of values against the case variable. The code below is an example:

food = gets.chomp
case food
when "plantain","beans"
  puts "You ate beans or plantain"
when 'rice'
    puts "I ate rice"
else
    puts "#{food} wasn't handled by when"
end

when the when statement is separated with a comma, it checks to see if any of the when values matches the value of the case statement. So in this case, if the user inputs plantain, "You ate beans or plantain would be printed"

Thanks for reading through. Hope you learnt a little bit about Ruby and its intuitiveness😋