From: Robert Klemme Date: 2006-02-22T22:08:32+09:00 Subject: Re: A regexp for an include? method Boucher, Eric wrote: > Hi, > > I want to see if a certain pattern is inside an array. I tried: > myArray.flatten.include?(/myPattern/) > > but it always return false. Why? Is it because the "include?" doesn't > takes regular expressions? > Here's another example that I tried inside an irb session: > > data = ["TC_TP1", "TC_TP2", "TC_TP3"] > =>["TC_TP1", "TC_TP2", "TC_TP3"] > data.include?(/TC_TP/) > => false > data.include?(/TC_TP.*/) > => false > data.include?(/TC_TP1/) > => false > data.include?("TC_TP1") > => true !!! > > Thanks for your help. It's because include? uses #eql? or == for comparison while regexp matching is done via === and =~. You can use #find, #select or #any? irb(main):042:0> data.find {|x| /TC_TP/ =~ x} => "TC_TP1" irb(main):043:0> data.find {|x| /XTC_TP/ =~ x} => nil irb(main):044:0> data.select {|x| /XTC_TP/ =~ x} => [] irb(main):045:0> data.select {|x| /TC_TP/ =~ x} => ["TC_TP1", "TC_TP2", "TC_TP3"] irb(main):046:0> data.any? {|x| /TC_TP/ =~ x} => true irb(main):047:0> data.any? {|x| /YTC_TP/ =~ x} => false I'd go for any? as it short circuits, i.e. terminates after the first successful match. Kind regards robert