What are Conditionals?
Learn about conditionals in Ruby.
What are conditionals?
Sometimes, we only want to perform an action if a certain criterion is met. Other times, we may want to check for a certain condition and then do one thing or another based on the answer. If this is true, then do that. Otherwise, do something else.
All practical programming languages have some way of expressing this, and in Ruby, it looks like this:
Press + to interact
Ruby
number = 5if number.between?(1, 10)puts "The number is between 1 and 10"elsif number.between?(11, 20)puts "The number is between 11 and 20"elseputs "The number is bigger than 20"end
It should be clear what this does and how it works.
Explanation
Let’s walk through it step by step:
-
Running this code prints out
The number is between 1 and 10
because the ...