【问题标题】:Match a pattern in an array匹配数组中的模式
【发布时间】:2012-05-10 00:01:24
【问题描述】:

有一个包含 2 个元素的数组

test = ["i am a boy", "i am a girl"]

我想测试是否在数组元素中找到了一个字符串,比如:

test.include("boy")  ==> true
test.include("frog") ==> false

我可以这样吗?

【问题讨论】:

    标签: ruby arrays


    【解决方案1】:

    使用正则表达式。

    test = ["i am a boy" , "i am a girl"]
    
    test.find { |e| /boy/ =~ e }   #=> "i am a boy"
    test.find { |e| /frog/ =~ e }  #=> nil
    

    【讨论】:

    • @izomorphius 是的,但发帖人没有指定字符串是否必须是单独的单词。使用不同的正则表达式很容易修复。
    • 事实上我在创建另一个正则表达式时遇到了一些麻烦。你怎么说字符串结尾或\w?
    【解决方案2】:

    你可以像这样 grep(正则表达式):

    test.grep /boy/
    

    甚至更好

    test.grep(/boy/).any?
    

    【讨论】:

    • 反转它会更有效,即将match传递给any?,因此它不必检查所有字符串。
    【解决方案3】:

    你也可以这样做

    test = ["i am a boy" , "i am a girl"]
    msg = 'boy'
    test.select{|x| x.match(msg) }.length > 0
    => true
    msg = 'frog'
    test.select{|x| x.match(msg) }.length > 0
    => false
    

    【讨论】:

      【解决方案4】:

      我使用 Peters sn-p 并对其进行了一些修改以匹配字符串而不是数组值

      ary = ["Home:Products:Glass", "Home:Products:Crystal"]
      string = "Home:Products:Glass:Glasswear:Drinking Glasses"
      

      使用:

      ary.partial_include? string
      

      数组中的第一项将返回true,它不需要匹配整个字符串。

      class Array
        def partial_include? search
          self.each do |e|
            return true if search.include?(e.to_s)
          end
          return false
        end
      end
      

      【讨论】:

      • 奇怪的是,我在 ruby​​ 核心类 Array 中也需要这个。
      【解决方案5】:

      如果你不介意对 Array 类进行猴子补丁,你可以这样做

      test = ["i am a boy" , "i am a girl"]
      
      class Array
        def partial_include? search
          self.each do |e|
            return true if e[search]
          end
          return false
        end
      end
      
      p test.include?("boy") #==>false
      p test.include?("frog") #==>false
      
      p test.partial_include?("boy") #==>true
      p test.partial_include?("frog") #==>false
      

      【讨论】:

      • 我不一定会说这本身就是“最好的”方式,因为在所有其他 ruby​​ 代码/项目中也可以使用类修改。这绝对是一种方式。
      【解决方案6】:

      如果你想测试一个单词是否包含在数组元素中,你可以使用这样的方法:

      def included? array, word
        array.inject([]) { |sum, e| sum + e.split }.include? word
      end
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-08-26
        • 2017-12-16
        • 1970-01-01
        • 1970-01-01
        • 2019-12-10
        相关资源
        最近更新 更多