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.
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 thewhen
statement uses to compare values. - If any of the
when
statements matches the value of thefood
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 theend
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:
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:
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😋