Why should you avoid the then keyword in Ruby?

Several Ruby style guides mention that you should never use. Personally, I think the β€œthen” keyword allows you to make the code denser, which is usually harder to read. Are there any other reasons for this recommendation?

+7
source share
3 answers

I almost never use the then keyword. However, there is one case where I believe that it significantly improves readability. Consider the following conditional conditional if statements.

Example A

 if customer.jobs.present? && customer.jobs.last.date.present? && (Date.today - customer.jobs.last.date) <= 90 puts 'Customer had a job recently' end 

The line length is too long. Hard to read.

Example B

 if customer.jobs.present? && customer.jobs.last.date.present? && (Date.today - customer.jobs.last.date) <= 90 puts 'Customer had a job recently' end 

Where conditions end and where the internal code begins. Following the instructions of the Ruby Style Guides, you should have one extra space for segments for multi-line conditional expressions, but I still don't find it easy to read.

Example C

 if customer.jobs.present? && customer.jobs.last.date.present? && (Date.today - customer.jobs.last.date) <= 90 then puts 'Customer had a job recently' end 

For me, the C example is by far the clearest. And using the then tag does the trick.

+8
source

If I remember correctly, then is only one of the delimiters to separate the condition from the true part (semicolon and new line are others)

If you have an if statement that is single-line, you will have to use one of the delimiters.

if (1==2) then puts "Math doesn't work" else puts "Math works!" end

for multi-line ifs, then is optional (a new line works)

 if (1==2) puts "Math doesn't work" else puts "Math works!" end 

Could you post a link to one of the style guides you mentioned ...

+6
source

I think that "never use then " is wrong. Using too many characters other than the alphabet can make the code difficult to read as perl or APL. Using the word natural language often makes the programmer more comfortable. It depends on the balance between code readability and compactness. The ternary operator is sometimes convenient, but if used improperly, it is ugly.

+2
source

All Articles