Ruby if .. elsIf .. else 在一行上?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13848780/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 05:35:55  来源:igfitidea点击:

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

rubylogic

提问by Noz

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

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

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

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

但是如果我想把它写成这样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?

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

回答by sawa

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

or

或者

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

回答by sunnyrjuneja

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

Github上的Ruby风格指南建议一个衬垫用于琐碎if / else语句,并且可以避免嵌套三元运营商保留。您可以使用then关键字,但它被认为是不好的做法。

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.

如果发现您的控制语句过于复杂,您可以使用 case(ruby 的 switch 运算符)。

回答by tjmw

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

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

回答by tokland

You can also write:

你也可以写:

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

However, this isn't idiomatic formatting in Ruby.

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