32
loading...
This website collects cookies to deliver better user experience
IF/ELSE
: this is the most important flow control. If a condition is met (true), then it will do something; otherwise, it will do something else - a classic one.age = 14
if age >= 18
puts "You can vote"
else
puts "You can't vote"
end
# => "You can't vote
ELSEIF
: is used when you have more than one condition to evaluate. For example:digit = 1
if digit == 0
puts "Zero"
elsif digit == 1
puts "One"
else
puts "I don't know this digit,sorry!"
end
# => "One"
Unless
: is the exact opposite of 'if'. 'If' will execute when the statement is true. 'unless' on the other hand will execute when the statement is false:age = 14
unless age >= 18
puts "You can't vote"
else
puts "You can vote"
end
# => "You can vote
CASE/WHEN
: is very similar to if / else expression. The premise is very similar:digit = 1
case
when digit == 0
puts "Zero"
when digit == 1
puts "One"
else
puts "I don't know this digit,sorry!"
end
# => 1
== Equal
!= Not equal
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
1 == 1
# => true
1 == 2
# => false
and and &&
or and ||
not and !
a = 1
b = 2
if a == 1 && b == 2
puts "True"
end
# => "True"
a = 1
b = 2
if a == 1 && b == 1
puts "True"
else
puts "False"
end
# => "False"
a = 1
b = 2
if a == 1 || b == 1
puts "True"
else
puts "False"
end
# => "True"
1 == 1
!(1 == 1)
# => true
# => false
a = 1
a == 1 ? true : false
# => true Let's break this down. First, Ruby evaluates whether the statement a == 1 is true or false. If it is true, the code to the left of : gets executed. If the statement is false, the code to the right of : gets executed. You can see it is very similar to an if / else statement, and it is much easier to implement and read.