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"
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
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"
3条答案
按热度按时间vdzxcuhz1#
您可以通过使用guard子句组合使用模式匹配和@Rajagopalan建议的
any?
。否则我们可以玩些奇怪的把戏比如
4xy9mtcn2#
用这种方式。使用
any?
方法。ve7v8dk23#
如果只有某种管道splat
*|THINGS
存在: