红宝石:条件矩阵?有多个条件的情况? [英] Ruby: conditional matrix? case with multiple conditions?

查看:11
本文介绍了红宝石:条件矩阵?有多个条件的情况?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆