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

爷,独闯天下 提交于 2019-11-29 11:04:50

问题


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?


回答1:


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

or

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



回答2:


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.




回答3:


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




回答4:


You can also write:

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

However, this isn't idiomatic formatting in Ruby.



来源:https://stackoverflow.com/questions/13848780/ruby-if-elsif-else-on-a-single-line

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!