使用 Ruby 3 哈希模式匹配,是否可以指定
rest
仅包含允许的键?
到目前为止我只想到了这个:
opts = { value: 5, limit: 10 } # valid
# opts = { value: 5 } # valid
# opts = { value: 5, foo: 10 } # not valid
case opts
in value:, **rest if rest.nil? || (rest.keys - %i[limit]).empty?
end
受 Flowtype 启发的东西可能是
in value:, limit?:
甚至
in value: Integer, limit?: Integer
也许我误解了这个问题,但您可以指定多种模式,例如:
options = [{ value: 5, limit: 10 }, # valid
{ value: 5 },
{ value: 5, foo: 10 }]
outputs = options.map do |opts|
{opts: opts,
matched: case opts
in {value: Integer, **nil}
'matched value'
in {value: Integer, limit: Integer, **nil}
'matched value and limit'
else
'no match'
end}
end
#=> [{:opts=>{:value=>5, :limit=>10}, :matched=>"matched value and limit"},
# {:opts=>{:value=>5}, :matched=>"matched value"},
# {:opts=>{:value=>5, :foo=>10}, :matched=>"no match"}]
看起来符合要求。