You may recall the alternative syntax for while
loops mentioned in Chapter 5. Instead of writing this:
while tired do sleep end
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:
puts( "somevar = #{somevar}" ) if DEBUG
18.226.251.70