Ruby:条件矩阵? 有多种情况的情况?

在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 

……但那不起作用。 那么,处理这种情况的最佳方法是什么?

布尔情况(在这种case没有表达式,它返回带有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的第一个分支):

 result = case [A, B] when [true, true] then ... when [true, false] then ... when [false, true] then ... when [false, false] then ... end 

如果您正在寻找具有一个条件但多个匹配器的案例..

 case @condition when "a" or "b" # do something when "c" # do something end 

..然后你真的需要这个

 case @condition when "a", "b" # do something when "c" # do something end 

这可以改写为

 case @condition when ("a" and "b") # do something when "c" # do something end 

但这有点违反直觉,因为它相当于

 if @condition == "a" or @condition == "b" 

不确定是否有标准的Ruby方式,但您可以随时将它们转换为数字:

 val = (a ? 1 : 0) + (b ? 2 : 0) case val when 0 then ... when 1 then ... when 2 then ... when 3 then ... end 

或者有一系列的procs数组和do

 my_procs[a][b].call()