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

Noz picture Noz · Dec 12, 2012 · Viewed 37.3k times · Source

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?

Answer

sawa picture sawa · Dec 12, 2012
a = (foo && "a" or bar && "b" or "c")

or

a = ("a" if foo) || ("b" if bar) || "c"