DEV Community

jason ho
jason ho

Posted on

TIL ternary operator

I found ternary operator when tried to use conditional statements inside create()

condition ? expression_if_true : expression_if_false
Enter fullscreen mode Exit fullscreen mode

Simple boolean condition:

x > 0 ? "positive" : "non-positive"
Enter fullscreen mode Exit fullscreen mode

Checking for nil:

result = value.nil? ? "Value is nil" : "Value is not nil"
Enter fullscreen mode Exit fullscreen mode

Nested ternary operators:

grade = score > 90 ? "A" : (score > 80 ? "B" : "C")
Enter fullscreen mode Exit fullscreen mode

Assigning a default value:

name = user_name ? user_name : "Guest"
# or, using the ternary operator
name = user_name || "Guest"
Enter fullscreen mode Exit fullscreen mode

Using ternary in method arguments:

puts x > 0 ? "Positive" : "Non-positive"
Enter fullscreen mode Exit fullscreen mode

Top comments (0)