What is the purpose of using the "if" suffix in Ruby?

I know that Ruby supports the if suffix as:

 number = -42 if opposite 

but what is the purpose of this? Why will it be used instead of the if prefix instruction?

+6
source share
5 answers

The suffix-style if and unless can also be useful for "protective sentences" in the form:

 return if ... return unless ... 

Here is an example:

 # suffix-style def save return false if invalid? # go for it true end 

Versus:

 # indented style def save if valid? # go for it true else false end end 

In the second example, the entire implementation of the method must be indented by validation valid? , and we need an additional else clause. With suffix type invalid? check invalid? is considered a boundary case that we process and then exit the system, and the rest of the method does not require indentation or the else clause.

This is sometimes called a โ€œdefensive offerโ€ and is recommended in the Ruby style guide.

+6
source

This may make it easier to read the code in some cases. I believe that this is true, especially in the case of unless , where you have some kind of action that you usually want to perform:

 number = -42 unless some_unusual_circumstance_holds 

Once you have unless , it makes sense for symmetry to support it for if .

+3
source
 number = -42 if opposite 

coincides with

 if opposite number = -42 end 

Some people prefer a single line font for readability. Imagine a line like:

 process_payment if order_fulfilled? 

Don't you like to read it?

+3
source

The Postfix style does not have an else section. This is useful when you only want to do something with one of two cases, divided by a condition, and donโ€™t want to mess with the other case.

+2
source

This is the same as the prefix, but shorter. The only reason is to save vertical space in a text editor.

+1
source

All Articles