From: "David A. Black" Date: 2008-07-07T07:08:34+09:00 Subject: Re: .include? for string Hi -- On Mon, 7 Jul 2008, Joel VanderWerf wrote: > Chris Chris wrote: >> Hi, >> >> I have an array a >> >> => [["abc", "def", "ghi|ghi|kl"], ["jkl", "mno", "ghi|pqr"], ["stu", >> "vwx", "yz|abc"]] >> >> Some strings contain the pipe character. >> >> I want to delete all the arrows that do NOT contain a certain string. >> >> I tried this: >> >> a.delete_if { |x| !x.include? "ghi|ghi" } >> >> => [] >> >> Of course, the array I need would be >> => [["abc", "def", "ghi|ghi|kl"]] > > Enumerable#grep can be helpful here. > > a = [["abc", "def", "ghi|ghi|kl"], ["jkl", "mno", "ghi|pqr"], ["stu", > "vwx", "yz|abc"]] > > a.delete_if { |x| x.grep(/ghi\|ghi/).empty? } > > p a # ==> [["abc", "def", "ghi|ghi|kl"]] > > Note that the '|' char needs to be escaped in a regex. > > Another option: > > a.delete_if { |x| x.all? { |s| not s.include? "ghi|ghi" }} > > Closer to the way you phrased the problem, but IMO a little less rubyesque. I kind of like this hybrid: >> def a.delete_unless(&block); replace select(&block); end => nil >> a.delete_unless {|ary| ary.include? {|string| string.include?("ghi|ghi") }} => [["abc", "def", "ghi|ghi|kl"]] David -- Rails training from David A. Black and Ruby Power and Light: Intro to Ruby on Rails July 21-24 Edison, NJ Advancing With Rails August 18-21 Edison, NJ See http://www.rubypal.com for details and updates!