16

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?
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Apollys supports Monica
  • 2,938
  • 1
  • 23
  • 33
  • @Apollys I haven't downvoted or voted to close since I'm not sure. If I did either, I would explicitly say so. The link was just a suggestion. Take it or leave it. – Carcigenicate Apr 22 '17 at 01:33
  • @Carcigenicate Okay, coincidental timing then, my apologies kind sir. I did read that topic before posting this. (But notice that I wrote "I am aware of the classic ternary conditional...") – Apollys supports Monica Apr 22 '17 at 01:42
  • 1
    The duplicate *does* answer your question, including an answer that links to a style guide. – Martijn Pieters Apr 22 '17 at 09:52

2 Answers2

23

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.
Darkstarone
  • 4,590
  • 8
  • 37
  • 74
0

Ruby is very flexible and is often used to create Domain Specific Languages (DSLs), and while this example is not really a DSL, you could use it to create a more expressive ternary method on the object class.

def the_value(val, as_long_as:, otherwise:)
  as_long_as ? val : otherwise
end

some_thing = the_value 4, as_long_as: 1 > 0, otherwise: 5
=> 4
some_thing = the_value 4, as_long_as: 1 < 0, otherwise: 5
=> 5

You can change the method name, and parameters to fit whatever context you prefer.

ps: this assumes a ruby version >= 2.1

nPn
  • 16,254
  • 9
  • 35
  • 58