Match a pattern in an array
有一个包含2个元素的数组
1 | test = ["i am a boy","i am a girl"] |
我想测试是否在数组元素中找到字符串,比如:
1 2 | test.include("boy") ==> true test.include("frog") ==> false |
我能那样做吗?
使用正则表达式。
1 2 3 4 | 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(regex):
1 | test.grep /boy/ |
甚至更好
1 | test.grep(/boy/).any? |
你也可以做
1 2 3 4 5 6 7 | 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 |
我取了peters片段并对其进行了一些修改,以匹配字符串而不是数组值。
1 2 | ary = ["Home:Products:Glass","Home:Products:Crystal"] string ="Home:Products:Glass:Glasswear:Drinking Glasses" |
用途:
1 | ary.partial_include? string |
数组中的第一个项将返回true,它不需要匹配整个字符串。
1 2 3 4 5 6 7 8 | class Array def partial_include? search self.each do |e| return true if search.include?(e.to_s) end return false end end |
如果您不介意MonkeyPatch数组类,可以这样做
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | 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 |
如果要测试数组元素中是否包含单词,可以使用如下方法:
1 2 3 | def included? array, word array.inject([]) { |sum, e| sum + e.split }.include? word end |
如果您只是在寻找一个直接匹配,那么
检查Ruby中的数组中是否存在值