if and unless Modifiers

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: ...

Get The Book of Ruby now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.