It\'s mentioned in several Ruby style guides that you should \"Never use then.\" Personally, I think the \"then\" keyword allows you to make code denser, which tends to be
If I remember correctly, then
is just one of the delimiters to separate the condition from the true part (semicolon and newline being the others)
if you have an if statement that is a one-liner, you'd 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 (newline 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 that you mention...
I almost never use the then
keyword. However, there is one case where I believe it greatly improves readability. Consider the following multi 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
Line length 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 do the conditions end and where does the inner code begin. According to must Ruby Style Guides, you to have one extra space of indentation for multi line conditionals, but I still don't find it all the 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
To me, Example C is by far the most clear. And it is the use of the then
that does the trick.
I think "never use then
" is wrong. Using too much non-alphabet characters can make code as difficult to read as perl or APL. Using a natural language word often makes the programmer more comfortable. It depends on the balance between readability and compactness of the code. Ternary operator is occasionally convinient, but is ugly if misused.