Search code examples
ruby

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


What's the difference between these two Ruby if statements when we put a then at the end of the if statement?

if(val == "hi") then
  something.meth("hello")
else
  something.meth("right")
end

and

if(val == "hi")
  something.meth("hello")
else
  something.meth("right")
end

Solution

  • 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