Forum: Ruby Extract common entries in two arrays

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Iñaki Baz C. (Guest)
on 2009-03-15 01:32
(Received via mailing list)
Hi, how to get an array with just common entries from two arrays?:

  array1 = ["q", "w", "e", "r", "t", "y"]
  array2 = ["w", "t", "z"]

I want to get:

  array_common = ["w", "t"]

I don0t find an ellegant and fast way to get it. Any help?
Thanks a lot.
Iñaki Baz C. (Guest)
on 2009-03-15 01:38
(Received via mailing list)
El Domingo, 15 de Marzo de 2009, Iñaki Baz C. escribió:
> Hi, how to get an array with just common entries from two arrays?:
>
>   array1 = ["q", "w", "e", "r", "t", "y"]
>   array2 = ["w", "t", "z"]
>
> I want to get:
>
>   array_common = ["w", "t"]

array_common = array1 - (array1 - array2)
=> ["w", "t"]

:)
Ben B. (Guest)
on 2009-03-15 01:40
(Received via mailing list)
On Sat, Mar 14, 2009 at 4:34 PM, Iñaki Baz C. 
<removed_email_address@domain.invalid> wrote:
>>   array1 = ["q", "w", "e", "r", "t", "y"]
>>   array2 = ["w", "t", "z"]
>>
>> I want to get:
>>   array_common = ["w", "t"]
>
> array_common = array1 - (array1 - array2)
> => ["w", "t"]

Easier:

  array1 & array2
  => ["w", "t"]

Ben
Iñaki Baz C. (Guest)
on 2009-03-15 01:42
(Received via mailing list)
El Domingo, 15 de Marzo de 2009, Ben B.
escribió:> Easier:
>
>   array1 & array2
>   => ["w", "t"]

Great!
Harry K. (Guest)
on 2009-03-15 03:10
(Received via mailing list)
On Sun, Mar 15, 2009 at 8:29 AM, Iñaki Baz C. 
<removed_email_address@domain.invalid> wrote:
> Thanks a lot.
>
> --
> Iñaki Baz C.
>
>

array1 & array2

Harry
This topic is locked and can not be replied to.