MC logo

Conditional II

  Ruby Example Code

<<Conditional I if2.rb While Loop>>
# 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"

# Now toss the coin.
toss = if rand(2) == 1 then

# Report.
print "Toss was ", toss, ".\n"
print "You Win!\n" if hort == toss
See:Ruby Manual

Some more amazing if lore:
  1. The unless keyword is like if, but uses the opposite sense of the test: The code is run if the test is false.
  2. As with many things in Ruby, if may look like a statement, but it is actually an expression, with a return value.
  3. The if has a postfix form where the condition comes last. This works with unless as well.
<<Conditional I While Loop>>