Tenary Operator (RUBY) | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Tenary Operator (RUBY)

How do they work in ruby? I'm getting an error foo = hitchhiker ? 42 : 3.1415 // Assign result of ?: to a variable puts(hitchhiker ? 42 : 3.1415) // Pass result as argument return hitchhiker ? 42: 3.1415 // Return result

27th Nov 2022, 5:18 PM
Watermelon
Watermelon - avatar
2 Answers
+ 3
They work like you typed them, except for the last one. You need a function to use return, and hitchhiker needs to be true or false: hitchhiker = true foo = hitchhiker ? 42 : 3.1415 # Assign result of ?: to a variable puts(hitchhiker ? 42 : 3.1415) # Pass result as argument #return hitchhiker ? 42: 3.1415 # Return result puts(foo)
27th Nov 2022, 5:40 PM
Paul
Paul - avatar
+ 2
Conditional (ternary) operator - takes three operands: a condition followed by a question mark (?), then an expression that executes if the condition is true is followed by a colon (:), and finally an expression that executes if the condition is false
27th Nov 2022, 5:35 PM
Yaroslav Vernigora
Yaroslav Vernigora - avatar