有一个包含 2 个元素的数组
test = ["i am a boy", "i am a girl"]
我想测试是否在数组元素中找到了一个字符串,比如:
test.include("boy") ==> true
test.include("frog") ==> false
我可以那样做吗?
使用正则表达式。
test = ["i am a boy" , "i am a girl"]
test.find { |e| /boy/ =~ e } #=> "i am a boy"
test.find { |e| /frog/ =~ e } #=> nil
那么你可以像这样grep(正则表达式):
test.grep /boy/
甚至更好
test.grep(/boy/).any?
你也可以做
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
我拿了彼得斯片段并对其进行了一些修改以匹配字符串而不是数组值
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
如果您不介意对 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
如果你想测试一个单词是否包含在数组元素中,你可以使用这样的方法:
def included? array, word
array.inject([]) { |sum, e| sum + e.split }.include? word
end