我想创建一个检查多个参数的case
。
"Ruby:条件矩阵?有多个条件的大小写?"基本上只有一个扭曲:第二个参数可以是三个值之一,a
、b
、nil
。
我希望将when
条件扩展为类似于:
result = case [A, B]
when [true, ‘a’] then …
when [true, ‘b’] then …
when [true, B.nil?] then …
end
有什么建议吗?
评论中已经是您对nil
:的特定测试的答案
result = case [A, B]
when [true, 'a'] then …
when [true, 'b'] then …
when [true, nil] then …
end
但你的问题启发了我一个更深入的问题:如果第二个参数可以是什么呢?例如,您有以下决策表:
A B result
------------------
a b true
a _ halftrue
_ b halftrue
else false
其中_
是任何的指示符
一个可能的解决方案是一个类,它等于一切:
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]
}
结果:
a b: true
a x: halftrue
x b: halftrue
x y: false