Ruby: conditional matrix? case with multiple conditions? Ruby: conditional matrix? case with multiple conditions? ruby ruby

Ruby: conditional matrix? case with multiple conditions?


Boolean case (with no expression in the case, it returns the first branch with a truthy when_expr):

result = casewhen 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 somethingend

..then you actually need this:

case @condition  when "a", "b"    # do something  when "c"    # do somethingend

This can be rewritten as

case @condition  when ("a" and "b")    # do something  when "c"    # do somethingend

But this is somewhat counter-intuitive, as it's equivalent to

if @condition == "a" or @condition == "b"


Not sure if there's a standard Ruby way, but you can always turn them into a number:

val = (a ? 1 : 0) + (b ? 2 : 0)case val  when 0 then ...  when 1 then ...  when 2 then ...  when 3 then ...end

or have an array of arrays of procs and do

my_procs[a][b].call()