在 ruby 中,我想知道是否有办法执行以下操作:
我基本上有一个包含四种可能结果的矩阵:
A is True, B is True
A is True, B is False
A is False, B is True
A is False, B is False
我想用尽可能干净的“ruby 方式”为此编写一个测试。
我希望做一些类似的事情
case[A,B]
when A && B then ...
when A && !B then ...
when !A && B then ...
when !A && !B then ...
end
...但这不起作用。那么,处理这种情况的最佳方法是什么?
最佳答案
bool 案例(在 case
中没有表达式,它返回带有 truthy when_expr
的第一个分支):
result = case
when A && B then ...
when A && !B then ...
when !A && B then ...
when !A && !B then ...
end
匹配case(在case
中有一个表达式,它返回满足谓词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
关于Ruby:条件矩阵?有多个条件的情况?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5111106/