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?
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
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