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.

516<br />

Creating Functions<br />

If you don’t know how many times you need to repeat commands, use a<br />

WHILE loop, which looks like this<br />

while condition<br />

Command<br />

end<br />

If the condition is True, the loop runs at least once. If this condition is<br />

False, then the loop doesn’t run.<br />

Ruby also offers a negated <strong>for</strong>m of the WHILE loop called an UNTIL loop,<br />

which looks like this:<br />

until condition<br />

Command<br />

end<br />

The UNTIL loop keeps running until a condition becomes True.<br />

Somewhere inside a WHILE or an UNTIL loop, you must have a command<br />

that can change the condition from True to False; otherwise the loop will<br />

never end and your program will appear to hang or freeze.<br />

Creating Functions<br />

To break up <strong>programming</strong> problems, you can create subprograms that solve<br />

a specific task. Such subprograms are functions or methods. The <strong>for</strong>mat of a<br />

typical function looks like this:<br />

def functionname (Parameter list)<br />

Commands<br />

return value<br />

end<br />

The two parts of a Ruby function are<br />

✦ Parameter list: Defines any data that the function needs to work. If<br />

the function doesn’t need to accept any values, omit the parentheses<br />

altogether.<br />

✦ Return: Defines a value to return.<br />

If a function doesn’t return a value or accept any parameters, it might look<br />

like this:<br />

def myfunction<br />

Command<br />

end

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

Saved successfully!

Ooh no, something went wrong!