我正在尝试对哈希进行模式匹配。我想知道哈希是否有一个键,其字符串值位于已知字符串数组中
这是我到目前为止所拥有的:
THINGS = %w[red orange yellow]
hash = {foo: 'yellow'}
case hash
in {foo: THINGS}
# I want this to match but it doesn't
else
# ..
end
这可以通过模式匹配实现吗?
用这种方式。使用
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