Ruby if .. elsIf .. else在一行上吗? [英] Ruby if .. elsIf .. else on a single line?

查看:110
本文介绍了Ruby if .. elsIf .. else在一行上吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

但是如果我想将其写为if foo 'a' elsif bar 'b' else 'c'怎么办?

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"

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

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?

推荐答案

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

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

这篇关于Ruby if .. elsIf .. else在一行上吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆