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?
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
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
If you're looking for a case with one condition but multiple matchers..
case @condition when "a" or "b" # do something when "c" # do something end
..then you actually need this:
case @condition when "a", "b" # do something when "c" # do something end
This can be rewritten as
case @condition when ("a" and "b") # do something when "c" # do something end
But this is somewhat counter-intuitive, as it's equivalent to
if @condition == "a" or @condition == "b"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With