我可以做hash.has_key吗?('video'或'video2')(红宝石)

Rad*_*dek 7 ruby hash

甚至更好的我可以hash.has_key?('videox')在x所在的地方做

  • "没什么,或者
  • 一个数字?

所以'视频','video1','video2'会通过这个条件?

当然我可以有两个条件,但万一我需要使用video3将来会变得更复杂......

mik*_*kej 12

如果您希望视频的一般情况后跟数字而没有明确列出所有组合,则可以使用Enumerable中的一些方法将它们与正则表达式结合使用.

hash.keys是从键阵列hash^video\d$匹配视频后跟数字.

# true if the block returns true for any element    
hash.keys.any? { |k| k.match(/^video\d$/ }
Run Code Online (Sandbox Code Playgroud)

要么

# grep returns an array of the matching elements
hash.keys.grep(/^video\d$/).size > 0
Run Code Online (Sandbox Code Playgroud)

grep 如果您需要代码的下一位信息,例如,您还可以捕获匹配的密钥

if (matched_keys = hash.keys.grep(/^video\d$/)).size > 0
  puts "Matching keys #{matched_keys.inspect}"
Run Code Online (Sandbox Code Playgroud)

此外,如果我们要查找的键的前缀是变量而不是硬编码字符串,我们可以执行以下操作:

prefix = 'video'
# use an interpolated string, note the need to escape the
# \ in \d
hash.keys.any? { |k| k.match("^#{prefix}\\d$") }
Run Code Online (Sandbox Code Playgroud)


Dig*_*oss 6

一种可能性:

hash.values_at(:a, :b, :c, :x).compact.length > 1
Run Code Online (Sandbox Code Playgroud)