liveBook · Manning

Conditional modifier

As explained in The Well-Grounded Rubyist, Fourth Edition

A conditional modifier is postfix Ruby syntax that conditionally executes a statement without enclosing it in a compound conditional block.

A conditional modifier places if or unless after a statement, so Ruby executes that statement only when the condition permits it. For a simple condition, this avoids an enclosing end. section 6.1.1

Postfix if and unless

puts "Big number!" if x > 100 is equivalent to a multiline if/end form. The inverse style, puts "Big number!" unless x <= 100, expresses the same kind of one-statement decision. section 6.1.1

Use conditional modifiers when:

  • The condition controls one straightforward statement. section 6.1.1
  • Avoid them when branching needs else or elsif, or when the trailing statement becomes long and difficult to read. section 6.1.1
if condition
  # code here, executed if, and only if, condition is true
end

Compare the postfix examples with the ordinary if/end structure to see how the modifier removes the enclosing block. section 6.1.1

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains postfix syntax, equivalent block forms, branching limits, and a readability warning.
Examples
Uses puts statements guarded by postfix if and unless, alongside equivalent multiline if/end code.
What you can do after
Apply it via Ruby syntax to write concise conditional statements and recognize when a block form reads better.
How it connects
Connects conditional modifiers to if, unless, else, elsif, and statement readability.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Rubyist, Fourth Edition. The section links point to the parts of the book it draws on.