匹配数组中的模式

时间:2012-04-30 09:11:51

标签: ruby arrays

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

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

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

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

我能这样做吗?

7 个答案:

答案 0 :(得分:45)

使用Regex。

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

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

答案 1 :(得分:36)

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

test.grep /boy/

甚至更好

test.grep(/boy/).any?

答案 2 :(得分:3)

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

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

答案 3 :(得分: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 :(得分:1)

如果要测试数组元素中是否包含单词,可以使用如下方法:

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

答案 5 :(得分:1)

如果您不介意monkeypatch 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

答案 6 :(得分:0)

如果您只是寻找直接匹配,则include?已在Ruby中提供。回答Stack Overflow上类似问题的帖子:

Check if a value exists in an array in Ruby

相关问题