Ruby has all the usual control structures, such as
if
statements
and
while
loops. Java, C, and Perl programmers may well get
caught by the lack of braces around the bodies of these
statements. Instead, Ruby uses the keyword
end
to signify the end
of a body.
if count > 10
puts "Try again"
elsif tries == 3
puts "You lose"
else
puts "Enter a number"
end
|
Similarly,
while
statements are terminated with
end
.
while weight < 100 and numPallets <= 30
pallet = nextPallet()
weight += pallet.weight
numPallets += 1
end
|
Ruby
statement modifiers are a useful shortcut if the body of an
if
or
while
statement is just a single expression. Simply
write the expression, followed by
if
or
while
and the
condition.
For example, here's a simple
if
statement.
if radiation > 3000
puts "Danger, Will Robinson"
end
|
Here it is again, rewritten using a statement modifier.
puts "Danger, Will Robinson" if radiation > 3000
|
Similarly, a
while
loop such as
while square < 1000
square = square*square
end
|
becomes the more concise
square = square*square while square < 1000
|
These statement modifiers should seem familiar to Perl programmers.