Ruby:将一个字符串与另一个可能是字符串或正则表达式的对象进行匹配

Ruby: matching a string against another object that may be a string or regexp

我正在编写一个例程,将字符串与对象列表进行比较,每个对象可能是另一个字符串或 RegExp。有没有一种优雅的、以 ruby 为中心的方式来处理这个问题?

现在,我正在做这样的事情:

def compare(str, thelist)
  thelist.any? do |item|
    case str
      when item then true
      else false
    end
  end
end

if compare("The String I am testing", ['I am not', /string/i])
  # got a match

这似乎工作得很好,但对我的口味来说感觉有点过于黑客化和冗长,所以我只是想知道是否有更好的方法来做到这一点。 (我对使用 instance_of 这样的东西不感兴趣? - 我想出了这个解决方案,因为 instance_of? 太丑了。)

使用 Ruby 2.2.2

提前致谢...

这是您方法的简化版本:

def compare(str, thelist)
  thelist.any? { |item| item.match(str) }
end

你可以这样简化:

def compare(str, thelist)
  thelist.any? { |item| item === str }
end