Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: One-Line If-Then-Else [duplicate]

Tags:

syntax

ruby

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:

  1. Is there a cleaner way than if a then b else c end to write a "wordsey" one-line if-then-else in Ruby?
  2. Is the ternary conditional or the wordsey version more appropriate for the Ruby paradigm?
like image 836
Apollys supports Monica Avatar asked Apr 22 '17 01:04

Apollys supports Monica


1 Answers

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:

  1. No.
  2. The ternary is preferred according to this, this, while the if-struct is preferred according to this, and this. Ruby does not have an official style guide, you won't find a concrete answer I'm afraid. Personally, I use the if-struct, as it reduces cognitive load, if being more verbose.

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.
like image 198
Darkstarone Avatar answered Oct 28 '22 05:10

Darkstarone