Reputation: 303
I want to create a case
checking multiple parameters.
"Ruby: conditional matrix? case with multiple conditions?"
is basically it with one twist: The second parameter can be one of three values, a
, b
, nil
.
I was hoping to just extend the when
conditions to be something like:
result = case [A, B]
when [true, ‘a’] then …
when [true, ‘b’] then …
when [true, B.nil?] then …
end
Any suggestions?
Upvotes: 0
Views: 73
Reputation: 27855
In the comments is already the answer for your specific test for nil
:
result = case [A, B]
when [true, 'a'] then …
when [true, 'b'] then …
when [true, nil] then …
end
But your question inspired me for a more extended question: What if the 2nd parameter could be anything? E.g. you have this decision table:
A B result
------------------
a b true
a _ halftrue
_ b halftrue
else false
where _
is a indicator for anything
A possible solution would be a class, that is equal to everything:
class Anything
include Comparable
def <=>(x);0;end
end
[
%w{a b},
%w{a x},
%w{x b},
%w{x y},
].each{|a,b|
result = case [a, b]
when ['a', 'b'] then true
when ['a', Anything.new] then :halftrue
when [Anything.new, 'b'] then :halftrue
else false
end
puts "%s %s: %s" % [a,b,result]
}
The result:
a b: true
a x: halftrue
x b: halftrue
x y: false
Upvotes: 1