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
我想以最干净的“红宝石方式”为此编写一个测试。
我希望做一些类似的事情
case[A,B]
when A && B then ...
when A && !B then ...
when !A && B then ...
when !A && !B then ...
end
...但这行不通。那么,处理这种情况的最佳方法是什么?
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".
I was hoping to do something like
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
布尔情况(
case
中没有表达式,它返回第一个带有 truthywhen_expr
的分支):匹配情况(
case
中带有表达式)case
,它返回满足谓词when_expr === case_expr
的第一个分支:Boolean case (with no expression in the
case
, it returns the first branch with a truthywhen_expr
):Matching case (with an expression in the
case
, it returns the first branch that satisfies the predicatewhen_expr === case_expr
):如果您正在寻找具有一个条件但多个匹配器的案例..
..那么您实际上需要这个:
这可以重写为
但这有点违反直觉,因为它相当于
If you're looking for a case with one condition but multiple matchers..
..then you actually need this:
This can be rewritten as
But this is somewhat counter-intuitive, as it's equivalent to
不确定是否有标准的 Ruby 方式,但你总是可以将它们转换为数字:
或者有一个 procs 数组的数组,然后执行
Not sure if there's a standard Ruby way, but you can always turn them into a number:
or have an array of arrays of procs and do