Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby if .. elsIf .. else on a single line?

Tags:

ruby

logic

With the ruby ternary operator we can write the following logic for a simple if else construct:

a = true  ? 'a' : 'b' #=> "a"

But what if I wanted to write this as if foo 'a' elsif bar 'b' else 'c'?

I could write it as the following, but it's a little difficult to follow:

foo = true
a = foo  ? 'a' : (bar ? 'b' : 'c') #=> "a"

foo = false
bar = true
a = foo  ? 'a' : (bar ? 'b' : 'c') #=> "b"

Are there any better options for handling such a scenario or is this our best bet if we wish to condense if..elsif..else logic into a single line?

like image 962
Noz Avatar asked Dec 12 '12 21:12

Noz


People also ask

How do you write if else in one line Ruby?

You can use:If @item. rigged is true, it will return 'Yes' else it will return 'No'.

Does Ruby have else if?

Ruby if...else Statement if expressions are used for conditional execution. The values false and nil are false, and everything else are true. Notice Ruby uses elsif, not else if nor elif. Executes code if the conditional is true.

How do you write or condition in Ruby?

In Ruby, “or” keyword returns the logical disjunction of its two operands. The condition becomes true if both the operands are true. It returns “true” when any one condition/expression is “true” and returns “false” only when all of them are “false”.

What are the conditional statements in Ruby?

Conditionals are formed using a combination of if statements and comparison and logical operators (<, >, <=, >=, ==, != , &&, ||) . They are basic logical structures that are defined with the reserved words if , else , elsif , and end . Note that elsif is missing an "e".


4 Answers

a = (foo && "a" or bar && "b" or "c")

or

a = ("a" if foo) || ("b" if bar) || "c"
like image 138
sawa Avatar answered Oct 07 '22 23:10

sawa


The Github Ruby Styleguide recommends that one liners be reserved for trivial if/else statements and that nested ternary operators be avoided. You could use the then keyword but its considered bad practice.

if foo then 'a' elsif bar then 'b' else 'c' end

You could use cases (ruby's switch operator) if find your control statements overly complex.

like image 26
sunnyrjuneja Avatar answered Oct 07 '22 23:10

sunnyrjuneja


a = if foo then 'a' elsif bar then 'b' else 'c' end

like image 5
tjmw Avatar answered Oct 07 '22 23:10

tjmw


You can also write:

x = if foo then 'a' elsif bar then 'b' else 'c' end

However, this isn't idiomatic formatting in Ruby.

like image 3
tokland Avatar answered Oct 08 '22 01:10

tokland