Ruby – Ternary Operator (single line If-Else statement)

Previously we saw how you could fit an if-else statement into a single line with the help of the “then” keyword. However there is another commonly used syntax that you could use instead, which is known as the ternary operator (:?). Ternary Operators are also used in other languages such as java and c#. The ternary operator syntax is essentially as follows:

{condition} ? {if-code-block} : {else-code-block}

Here’s an example:

def success_message
  puts "this is a success"
end

def fail_message
  puts "this is a failure"
end

def result 
  true
end

result ? success_message : fail_message    # this outputs "this is a success"

def result 
  false
end

result ? success_message : fail_message    # this outputs "this is a failure"