Reputation: 11736
I made a small test today:
> false && 1 || 2
> 2
> true && 1 || 2
> 1
So if we could already do with binary operators, why did we need a ternary ?
> false ? 1 : 2
> 2
> true ? 1 : 2
> 1
As it is not simply an alias and complicates parsing.
Upvotes: 0
Views: 138
Reputation: 369428
The conditional operator is needed in languages like C, because if
/else
is a statement, it doesn't evaluate to a return value. But in Ruby, everything is an expression, everything has a return value, there are no statements.
Therefore, you can always replace the conditional operator with a conditional expression:
foo = bar ? baz : qux
is exactly equivalent to
foo = if bar then baz else qux end
In C, you cannot write this, you'd have to write
if bar then foo = baz else foo = aux end
leading to code duplication. That's why you need the conditional operator in C. In Ruby, it is unnecessary.
Actually, since Ruby is an object-oriented language, all conditionals are unnecessary. You can just use polymorphism instead.
Upvotes: 1
Reputation: 943142
To deal with the specific case in your question…
What if 1
was different value, one that evaluated as false?
And in general:
No. You can always replace a ternary operator with an if/else
construct. That isn't as convenient though.
Upvotes: 3
Reputation: 160170
No language needs a ternary operator.
The ternary operator is a well-known language construct. IMO people generally expect it in script-ish(-looking) languages, so there it is. I don't see a huge reason to not have it.
Upvotes: 1