Ruby如果.. elsIf .. else在一行?

使用ruby三元运算符,我们可以为一个简单的if else构造编写以下逻辑:

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

但是如果我想把它写成if foo 'a' elsif bar 'b' else 'c'怎么办?

我可以把它写成如下,但它有点难以遵循:

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

有没有更好的选择来处理这种情况,或者如果我们希望将if..elif..else逻辑压缩成一行,这是我们最好的选择吗?

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

要么

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

Github Ruby Styleguide建议为简单的if / else语句保留一个衬里,并避免嵌套的三元运算符。 你可以使用then关键字,但它被认为是不好的做法。

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

如果发现控制语句过于复杂,您可以使用案例(ruby的switch操作符)。

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

你也可以这样写:

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

但是,这不是Ruby中惯用的格式。