红宝石:条件矩阵?有多个条件的情况? [英] Ruby: conditional matrix? case with multiple conditions?
问题描述
在 ruby 中,我想知道是否有办法执行以下操作:
In ruby, I was wondering if there's a way to do the following:
我基本上有四个可能结果的矩阵:
I have basically a matrix of four possible outcomes:
A is True, B is True
A is True, B is False
A is False, B is True
A is False, B is False
我想以最简洁的红宝石方式"为此编写一个测试.
I'd like to write a test for this in the cleanest possible "ruby way".
我希望做类似的事情
case[A,B]
when A && B then ...
when A && !B then ...
when !A && B then ...
when !A && !B then ...
end
...但这不起作用.那么,处理这种情况的最佳方法是什么?
... but that doesn't work. So, what's the best way to handle this kind of situation?
推荐答案
Boolean case(case
中没有表达式,它返回第一个带有truthy的分支<代码>when_expr):
Boolean case (with no expression in the case
, it returns the first branch with a truthy when_expr
):
result = case
when A && B then ...
when A && !B then ...
when !A && B then ...
when !A && !B then ...
end
匹配大小写(在case
中有表达式,返回第一个满足谓词when_expr === case_expr
的分支):
Matching case (with an expression in the case
, it returns the first branch that satisfies the predicate when_expr === case_expr
):
result = case [A, B]
when [true, true] then ...
when [true, false] then ...
when [false, true] then ...
when [false, false] then ...
end
这篇关于红宝石:条件矩阵?有多个条件的情况?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!