【问题标题】:How to check if a string includes any value of an array?如何检查字符串是否包含数组的任何值?
【发布时间】:2018-10-12 22:42:51
【问题描述】:

我的字符串是

str = "my string is this one"

我的数组是

arr = ["no", "nothing", "only", "is"]

所以,我的字符串在我的数组的值中包含 is,我想得到结果true

我该怎么做?

我想用include?遇见

【问题讨论】:

    标签: ruby-on-rails arrays ruby string include


    【解决方案1】:

    检查整个单词是否区分大小写:

    (str.split & arr).any?
    #⇒ true
    

    不区分大小写:

    [str.split, arr].map { |a| a.map(&:downcase) }.reduce(&:&).any?
    #⇒ true
    

    检查它是否包含arr 中的任何一个:

    arr.any?(&str.method(:include?))
    #⇒ true
    

    【讨论】:

      【解决方案2】:
      (str.downcase.split & arr.map(&:downcase)).any?
         #=> false
      

      如果已知所有字母大小写相同。

      (str.split & arr).any?
         #=> false
      

      【讨论】:

        【解决方案3】:

        这使用正则表达式。好消息是它是为您生成的 - 无需学习语法。其他好消息:它只遍历字符串一次。

        re = Regexp.union(arr)  #your own regular expression without screws or bolts
        p re.match?(str)  # => true
        

        【讨论】:

        • 我相信你需要单词边界。例如,str = "not"; arr = ["no"] 不应匹配。 (容易修复,不错的方法。)
        猜你喜欢
        • 2015-02-28
        • 2013-11-12
        • 2012-08-11
        • 1970-01-01
        • 2015-09-08
        • 1970-01-01
        • 1970-01-01
        • 2020-12-01
        相关资源
        最近更新 更多