visit
if
expressionif 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.
The
if
expression acts as a question and the outcome is determined by the answer to that question, with the help of the elsif
and else
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
The
statement evaluates anything we put in front of him, if the result returns if
true
the condition is accepted and the piece of code inside gets executed, if the result returns false
or nil
(null) then we continue with the next condition, in this case elsif
(else if) and the same process applies, if the result of elsif
is true
then it should output the message "time to play"
, and finally if no condition is true
, the else
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 if
true
:puts "it's true!" if 1 > 0
# returns "it's true"
alarm.sound = off if current_day = 'saturday' || current_day = 'sunday'
Unlike the
statement who checks for a if
value, the true
unless
statement does the opposite and checks for false
or nil
:unless cellphone.battery.percentage > 14
cellphone.start_charge
end
We can combine the
expression only with the unless
else
statement: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
, if
can be used as a modifier serving the same purpose but only executing itself when the result is unless
or false
nil:
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"
The
statement is another Ruby conditional that can be used as an alternative to case
, 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 case
when
expression contains each one of the conditions, if a condition returns true
, the code inside is executed and concludes with the end
statement, finally the else
expression acts as the default condition to be executed if none of the case conditions return true
.Links
If you made it this far i hope this article helped you in one way or another, thanks for reading!