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

标签 ruby matrix conditional switch-statement

在 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/

相关文章:

java - JoptionPane ShowConfirmDialog

ruby-on-rails - 如何修改 Active Admin 的 XML 和 XLSX 输出?

Ruby 内存使用情况 : Methodical Loop Versus Built In Loop

ruby-on-rails - Rails - authenticate_or_request_with_http_basic 自定义 "access denied"消息

javascript - 在 Ruby 中动态命名数组/哈希

performance - 优化循环 : huge arrays operations

c++ - 函数在我的矩阵中自动分配值

`printf` 内的条件语句

sql-server - SQL : Conditionally select column based on aggregate value

使用 RGB 颜色进行 MATLAB 绘图