如何对已知数组中的值进行模式匹配哈希?

问题描述 投票:0回答:1

我正在尝试对哈希进行模式匹配。我想知道哈希是否有一个键,其字符串值位于已知字符串数组中

这是我到目前为止所拥有的:

THINGS = %w[red orange yellow]

hash = {foo: 'yellow'}

case hash
in {foo: THINGS}
  # I want this to match but it doesn't
else
  # ..
end

这可以通过模式匹配实现吗?

ruby pattern-matching
1个回答
0
投票

用这种方式。使用

any?
方法。

THINGS = %w[red orange yellow]

hash = {foo: 'yellow'}

if THINGS.any? { |color| hash[:foo] == color }
  # This will match if the value of :foo is included in THINGS
else
  # ..
end
© www.soinside.com 2019 - 2024. All rights reserved.