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

20jt8wwn  于 12个月前  发布在  Ruby
关注(0)|答案(3)|浏览(113)

我正在尝试模式匹配哈希。我想知道散列是否有一个键,其字符串值在一个已知字符串数组中(沿着一些我正在工作的其他标准)。
以下是我到目前为止所做的:

THINGS = %w[red orange yellow]

hash = {foo: 'yellow'}

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

这可能与模式匹配吗?

vdzxcuhz

vdzxcuhz1#

您可以通过使用guard子句组合使用模式匹配和@Rajagopalan建议的any?

THINGS = %w[red orange yellow]

def foo_color_match(hash)
  case hash
  in foo: a if THINGS.any?(a)
   "matched #{a}"
  else
   'no_match'
  end
end

h = {foo: 'yellow'}
h1 = {foo: 'black'}

p foo_color_match(h)
#=> "matched yellow"
p foo_color_match(h1)
#=> "no match"

否则我们可以玩些奇怪的把戏比如

THINGS = %w[red orange yellow]

def foo_color_match(hash, color_palette: THINGS)
  m = color_palette.to_enum 
  def m.===(other) = member?(other)

  case hash
  in foo: ^m => a
   "matched #{a}"
  else
   'no_match'
  end
end

h = {foo: 'yellow'}
h1 = {foo: 'black'}

p foo_color_match(h)
#=> "matched yellow"
p foo_color_match(h1)
#=> "no match"
4xy9mtcn

4xy9mtcn2#

用这种方式。使用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
ve7v8dk2

ve7v8dk23#

THINGS = %w[red orange yellow]
hash = {foo: "yellow"}

case hash
in {foo: color} if THINGS in [*,^color,*]
  "Matched: #{color}"
else
  "No match"
end
#=> "Matched: yellow"

如果只有某种管道splat *|THINGS存在:

hash = {foo: "red"}

case hash
in {foo: "yellow"|"red"|"orange" => color}
  "Matched: #{color}"
else
  "No match"
end
#=> "Matched: red"

相关问题