What is the difference between “if” statements with “then” at the end?

then is a delimiter to help Ruby identify the condition and the true-part of the expression.

if condition then true-part else false-part end

then is optional unless you want to write an if expression in one line. For an if-else-end spanning multiple lines the newline acts as a delimiter to split the conditional from the true-part

# can't use newline as delimiter, need keywords
puts if (val == 1) then '1' else 'Not 1' end

# can use newline as delimiter
puts if (val == 1)
  '1'
else
  'Not 1'
end

Leave a Comment