15.04.2018 Views

programming-for-dummies

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

514<br />

Branching Statements<br />

Branching Statements<br />

The simplest branching statement is an IF statement that runs only one or<br />

more commands if a Boolean condition is True, such as<br />

if condition<br />

Command<br />

end<br />

If you write the entire IF statement on a single line, you must make sure you<br />

include the then keyword, such as<br />

if condition then Command end<br />

Ruby also includes a negated <strong>for</strong>m of the IF statement called the UNLESS<br />

statement that looks like this:<br />

unless condition<br />

Command<br />

end<br />

The UNLESS statement runs only if the condition is False.<br />

a = 5<br />

unless a < 1<br />

puts “This will print out.”<br />

end<br />

Because the condition a < 1 is False, the preceding UNLESS statement<br />

runs the command sandwiched between the UNLESS keyword and the END<br />

keyword.<br />

Both the IF and UNLESS statements can make the computer choose between<br />

two mutually exclusive sets of commands by including an ELSE keyword,<br />

such as<br />

if condition<br />

Command1<br />

else<br />

Command2<br />

end<br />

Although the IF-ELSE statement can only give the computer a choice of two<br />

groups of commands to run, the IF-ELSIF statement can offer the computer<br />

multiple groups of commands to run, such as<br />

if condition1<br />

Command<br />

elseif condition2

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!