What if
¶
An if
statement allows you to take different actions depending on which conditions are met. For example:
if city == "Toronto"
drinking_age = 19
else
drinking_age = 21
end
This says:
- if the city is equal to (
==
) “Toronto”, then setdrinking_age
to 19. - Otherwise (else) set
drinking_age
to 21.
true
and false
¶
Ruby has a notion of true and false. This is best illustrated through some example. Start irb and type the following (taking special note of the difference between =
and ==
):
shell> irb --simple-prompt
>> 3 > 2
=> true
>> 3 < 2
=> false
>> num = 4
=> 4
>> num == 4
=> true
>> city = "Toronto"
=> "Toronto"
>> city == "Toronto"
=> true
The if
statements evaluates whether the expression (e.g. ’city == “Toronto”) is true
or false
and acts accordingly.
Notice the difference between =
and ==
:
=
is an assignment operator, it allows to you assign a value to a variable. It will evaluate to the value assigned.==
is a comparison operator, it will evaluate to true or false, depending on whether both sides are equal or different.
Most common conditionals¶
Here is a list of some of the most common conditionals:
== | equal |
!= | not equal to |
> | greater than |
< | less than |
>= | greater than or equal to |
<= | less than or equal to |
String comparisons¶
How do these operators behave with strings? Well, ==
is string equality and >
and friends are determined by ASCIIbetical order.
What is ASCIIbetical order? The ASCII character table contains all the characters in the keyboard. It lists them in this order:
…012…789…ABC…XYZ…abc…xyz…Start irb and type these in:
shell> irb --simple-prompt
>> "9" < "D"
=> true
>> "a" < "b"
=> true
>> "h" == "h"
=> true
>> "H" == "h"
=> false
>> "Z" <= "b"
=> true
>> "j" != "r"
=> true
elsif
¶
elsif
allows you to add more than one condition. Take this for example:
if age >= 60
puts "Senior fare"
elsif age >= 14
puts "Adult fare"
elsif age > 2
puts "Child fare"
else
puts "Free"
end
Let’s go through this:
- If age is 60 or more, we give a senior fare.
- If that’s not true, but age is 14 or more, we give the adult fare.
- If that’s not true, but age is more than 2 we give the child fare.
- Otherwise we ride free.
Ruby goes through this sequence of conditions one by one. The first condition to hold gets executed. You can put as many elsif’s as you like.