Our daily life contains a set of conditionals whose job is to define us as individuals, these conditionals are introduced to us from the very first day:
if user.status == "online" puts "hello world" end
Ruby syntax provides the necessary elements to translate any conditional programming sequence into manageable and easy to read lines of code.
expression acts as a question and the outcome is determined by the answer to that question, with the help of the
statements, the possibilities are endless:
if user.mood == "happy" puts "time to study" elsif user.mood == "sad" puts "time to play" else puts "time to code" end
statement evaluates anything we put in front of him, if the result returns
the condition is accepted and the piece of code inside gets executed, if the result returns
(null) then we continue with the next condition, in this case
(else if) and the same process applies, if the result of
then it should output the message
, and finally if no condition is
"time to play"
statement is executed.
IF AS A MODIFIER
As with the example above, the difference here is that first we need to write the "answer" or the code to be executed, then we pass the
statement followed by the "question" or condition, which it's executed if the result is
puts "it's true!" if 1 > 0 # returns "it's true"
alarm.sound = off if current_day = 'saturday' || current_day = 'sunday'
statement who checks for a
statement does the opposite and checks for
unless cellphone.battery.percentage > 14 cellphone.start_charge end
We can combine the
expression only with the
unless job.isDone? puts "go back to work" else puts "good job!" end job.isDone = true # returns "good job!"
UNLESS AS A MODIFIER
Just as his relative
can be used as a modifier serving the same purpose but only executing itself when the result is
puts "it's not right!" unless 4 > 3 # 4 > 3 is true so code doesn't execute
alarm.sound = on unless current_time < "7:00am"
statement is another Ruby conditional that can be used as an alternative to
, it's most frequently used to structure and create efficient code when there is a wide number of possible outcomes:
if / unless
case fuel_level when 71...100 puts "Fuel Level: High" when 41...70 puts "Fuel Level: Medium" when 21...40 puts "Fuel Level: Low" else puts "Fuel Level: Very Low" end fuel_level: 12 # returns "Fuel Level: Very Low"
is the expression to be evaluated, the
expression contains each one of the conditions, if a condition returns
, the code inside is executed and concludes with the
statement, finally the
expression acts as the default condition to be executed if none of the case conditions return
If you made it this far i hope this article helped you in one way or another, thanks for reading!
Create your free account to unlock your custom reading experience.