Control Flow

Ternary Operator in Ruby

The ternary operator is used to return a value based on the result of a binary condition.

It takes in a binary condition as input, which makes it similar to an 'if-else' control flow block. It also, however, returns a value, behaving similar to a function.


Syntax
result = binaryCondition ? valueReturnedIfTrue : valueReturnedIfFalse;

Notes

The ternary cannot be used to execute code. It must be either returned in a function, or set equal to a variable with the same data type as the returned values.


Example
def findMaximum(a, b)
    #if a > b, it returns a, if not it returns b
    return (a > b) ? a : b
end

Add to Slack

< Exception Handling   |   Throw and Catch >

© 2019 SyntaxDB. All Rights Reserved.