32

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

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

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

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

我可以那样做吗?

4

6 回答 6

52

使用正则表达式。

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

test.find { |e| /boy/ =~ e }   #=> "i am a boy"
test.find { |e| /frog/ =~ e }  #=> nil
于 2012-04-30T09:15:22.320 回答
46

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

test.grep /boy/

甚至更好

test.grep(/boy/).any?
于 2012-04-30T09:16:13.820 回答
6

你也可以做

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
于 2013-10-02T21:27:49.260 回答
3

我拿了彼得斯片段并对其进行了一些修改以匹配字符串而不是数组值

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
于 2013-07-11T15:25:17.393 回答
2

如果您不介意对 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
于 2012-04-30T19:16:36.837 回答
1

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

def included? array, word
  array.inject([]) { |sum, e| sum + e.split }.include? word
end
于 2012-04-30T09:15:07.720 回答