2008/8/1 David A. Black <dblack / rubypal.com>:
> Hi --
>
> On Fri, 1 Aug 2008, Stefan Lang wrote:
>
>> 2008/8/1 Milo Thurston <knirirr / gmail.com>:
>>>
>>> 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

Given Milo's use case, he's only using strings, so it doesn't
matter. include? is clearer in this case, IMO.

Stefan