Following from the previous tutorial on Conditional Logic in Ruby, look at this example:
# Let the user guess.
print "Enter heads or tails? "
hort = gets.chomp
unless hort == 'heads' || hort == 'tails'
print "I _said_ heads or tails. Can't you read?\n"
exit(1)
end
# Now toss the coin.
toss = if rand(2) == 1 then
"heads"
else
"tails"
end
# Report.
print "Toss was ", toss, ".\n"
print "You Win!\n" if hort == toss
Some more amazing if lore:
- The
unlesskeyword is likeif, but uses the opposite sense of the test: The code is run if the test is false. - As with many things in Ruby,
ifmay look like a statement, but it is actually an expression, with a return value. - The
ifhas a postfix form where the condition comes last. This works withunlessas well.



