July 2011
Intermediate to advanced
400 pages
8h 46m
English
You may recall the alternative syntax for while loops mentioned in Chapter 5. Instead of writing this:
while tired do sleep end
you can write this:
sleep while tired
This alternative syntax, in which the while keyword is placed between the code to execute and the test condition, is called a while modifier. It turns out that Ruby has if and unless modifiers too. Here are a few examples:
if_unless_mod.rb
sleep if tired begin sleep snore end if tired sleep unless not tired begin sleep snore end unless not tired
The terseness of this syntax is useful when you repeatedly need to take some well-defined action if some condition is true. You might, for example, pepper your code with debugging output if a constant called DEBUG is true: ...
Read now
Unlock full access