I am wondering if there is a way in Ruby to write a one-line if-then-else statement using words as operators, in a manner similar to python's
a if b else c
I am aware of the classic ternary conditional, but I have the feeling Ruby is more of a "wordsey" language than a "symboley" language, so I am trying to better encapsulate the spirit of the language.
I also am aware of this method,
if a then b else c end
which is basically squishing a multi-liner onto one line, but the end
at the end of the line feels cumbersome and redundant. I think the ternary conditional would be preferable to this.
So for you who know Ruby well, is there a better way to write this? If not, which of the methods is the most Rubyesque?
The following questions are not addressed by the linked post:
if a then b else c end
to write a "wordsey" one-line if-then-else in Ruby?The two one liners that exist are the two you already described:
Ternary:
a ? b : c
if-struct:
if a then b else c end
So to answer your questions:
However, all the most of the style guides say ternary operators are fine for simple constructs:
Avoid the ternary operator (?:) except in cases where all expressions are extremely trivial.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With