ruby 匹配数组中的模式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10381113/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Match a pattern in an array
提问by Kit Ho
There is an array with 2 elements
有一个包含 2 个元素的数组
test = ["i am a boy", "i am a girl"]
I want to test if a string is found inside the array elements, say:
我想测试是否在数组元素中找到了一个字符串,比如:
test.include("boy") ==> true
test.include("frog") ==> false
Can i do it like that?
我可以这样做吗?
回答by ghoppe
Using 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
回答by Roger
Well you can grep (regex) like this:
好吧,您可以像这样 grep (正则表达式):
test.grep /boy/
or even better
甚至更好
test.grep(/boy/).any?
回答by Richard Luck
Also you can do
你也可以做
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
回答by Brett
I took Peters snippet and modified it a bit to match on the string instead of the array value
我采用了 Peters 片段并对其进行了一些修改以匹配字符串而不是数组值
ary = ["Home:Products:Glass", "Home:Products:Crystal"]
string = "Home:Products:Glass:Glasswear:Drinking Glasses"
USE:
用:
ary.partial_include? string
The first item in the array will return true, it does not need to match the entire 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
回答by peter
If you don't mind to monkeypatch the the Array class you could do it like this
如果你不介意对 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
回答by Flexoid
If you want to test if a word included into the array elements, you can use method like this:
如果要测试某个单词是否包含在数组元素中,可以使用如下方法:
def included? array, word
array.inject([]) { |sum, e| sum + e.split }.include? word
end
回答by tmarkiewicz
If you're just looking for a straight match, include?is already available in Ruby. Answer thread from a similar question on Stack Overflow:
如果您只是在寻找直接匹配,include?则在 Ruby 中已经可用。从 Stack Overflow 上的类似问题回答线程:

