Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: conditional matrix? case with multiple conditions?

Tags:

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?

like image 400
Andrew Avatar asked Feb 24 '11 22:02

Andrew


2 Answers

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 
like image 81
tokland Avatar answered Nov 15 '22 05:11

tokland


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" 
like image 25
Mattias Arro Avatar answered Nov 15 '22 05:11

Mattias Arro