Basic Structure and exercise:
age = 10
puts “You’re too young to use this system” if age < 18
output: You’re too young to use this system
age = 10
if age < 18
puts “You’re too young to use this system”
end
output: You’re too young to use this system
age = 10
if age < 18
puts “You’re too young to use this system”
puts “So we’re going to exit your program now”
exit
end
output: You’re too young to use this system
It’s worth noting that unless can work in exactly the same way because unless is just
the opposite of if:
age = 10
unless age >= 18
puts “You’re too young to use this system”
puts “So we’re going to exit your program now”
exit
end
output: You’re too young to use this system
It’s possible to nest logic too, as in this example:
age = 19
if age < 21
puts “You can’t drink in most of the United States”
if age >= 18
puts “But you can in the United Kingdom!”
end
end
Output:
You can’t drink in most of the United States
But you can in the United Kingdom!
if and unless also supply the else condition, used to delimit lines of code that you
want to be executed if the main expression is false:
age = 10
if age < 18
puts “You’re too young to use this system”
else
puts “You can use this system”
end
output:
You’re too young to use this system
?:, The Ternary Operator:
age = 10
type = age < 18 ? “child” : “adult”
puts “You are a ” + type
output: You are a child
The second line contains the ternary operator. It starts by assigning the result of an
expression to the variable, type. The expression is age < 18 ? “child” : “adult”. The
structure is as follows:
<condition> ? <result if condition is true> : <result if condition is false>
In our example, age < 18 returns as true, so the first result, “child”, is returned and
assigned to type. However, if age < 18 were to be false, “adult” would be returned.
Consider an alternative:
age = 10
type = ‘child’ if age < 18
type = ‘adult’ unless age < 18
puts “You are a ” + type
The double comparison makes it harder to read. Another alternative is to use the
multiline if/else option:
age = 10
if age < 18
type = ‘child’
else
type = ‘adult’
end
puts “You are a ” + type
age = 10
puts “You are a ” + (age < 18 ? “child” : “adult”)
Regards,
P.Raveendran