如果我有下面的If else语句
if a.present? && b.value == 'N'
b = test
elsif a.present? && b.value == 'Y'
b = guest
end
我可以为此编写三元运算
b = (a.present? && b.value == 'N') ? "test" : "guest"
但在这个三元运算符中,我不是在寻找== 'Y‘的条件,它可以是其他的'd’或'e‘。
如何更新三进制运算符,以便验证if和elsif中的两个条件?
发布于 2017-06-21 00:29:40
对于这样的事情,您可能想要使用一个简单的查找表来消除一些逻辑:
EQUIVALENT = {
'Y' => 'guest',
'N' => 'test'
}
if (a.present?)
b = EQUIVALENT[b.value] || b
end
如果忽略非映射的b
值,则|| b
部分可能不是必需的。
发布于 2017-06-21 00:21:27
b = case b.value
when 'N' then test
when 'Y' then guest
end if a.present?
到目前为止,这是唯一的答案。
发布于 2017-06-21 05:27:31
您可以使用三元运算符。然而,这并不意味着你应该这样做:
a.present? && (b.value == 'N' ? b = 'test' : b.value == 'Y' && b = 'guest')
下面是一个小测试:
class Object
def present?
true
end
end
class NilClass
def present?
false
end
end
a = true
class B
attr_accessor :value
end
b = B.new
b.value = 'Y'
a.present? && (b.value == 'N' ? b = 'test' : b.value == 'Y' && b = 'guest')
p b
# "guest"
https://stackoverflow.com/questions/44658133
复制相似问题