From: "David A. Black" Date: 2008-08-01T22:01:01+09:00 Subject: Re: Using array.select with grep Hi -- On Fri, 1 Aug 2008, Stefan Lang wrote: > 2008/8/1 Milo Thurston : >> Using irb I set up the following arrays: >> >>>> arr1 >> => ["one", "two", "three"] >>>> arr2 >> => ["two", "three", "four"] >> >> I would expect to be able to collect the elements of arr1 that are also >> in arr2 using select and grep, i.e. >> >>>> arr1.select { |y| arr2.grep(y) } >> => ["two", "three"] >> >> But what I actually get is: >> >>>> arr1.select { |y| arr2.grep(y) } >> => ["one", "two", "three"] >> >> What is my error or misunderstanding here? > > Because grep returns an empty array when it can't find the > given string. And an empty array (everything except false and nil, > actually) is true in Ruby. Use #include? instead: > > arr1.select { |y| arr2.include?(y) } No, that's not the same. >> array = %w{ one two three } => ["one", "two", "three"] >> array.grep(/e/) => ["one", "three"] >> array.include?("e") => false David -- Rails training from David A. Black and Ruby Power and Light: * Advancing With Rails August 18-21 Edison, NJ * Co-taught by D.A. Black and Erik Kastner See http://www.rubypal.com for details and updates!