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.
0f1f17ba297242e9d3c86d4cc0a6ea85?d=identicon&s=25 Iñaki Baz Castillo (Guest)
on 2009-03-15 00: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.
0f1f17ba297242e9d3c86d4cc0a6ea85?d=identicon&s=25 Iñaki Baz Castillo (Guest)
on 2009-03-15 00:38
(Received via mailing list)
El Domingo, 15 de Marzo de 2009, Iñaki Baz Castillo 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"]

:)
90a73d9875462aaa9fab2feffafbffe7?d=identicon&s=25 Ben Bleything (Guest)
on 2009-03-15 00:40
(Received via mailing list)
On Sat, Mar 14, 2009 at 4:34 PM, Iñaki Baz Castillo <ibc@aliax.net> 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
0f1f17ba297242e9d3c86d4cc0a6ea85?d=identicon&s=25 Iñaki Baz Castillo (Guest)
on 2009-03-15 00:42
(Received via mailing list)
El Domingo, 15 de Marzo de 2009, Ben Bleything
escribió:> Easier:
>
>   array1 & array2
>   => ["w", "t"]

Great!
2f4d4f9c35ea851bffb9a9cc2e086365?d=identicon&s=25 Harry Kakueki (Guest)
on 2009-03-15 02:10
(Received via mailing list)
On Sun, Mar 15, 2009 at 8:29 AM, Iñaki Baz Castillo <ibc@aliax.net> wrote:
> Thanks a lot.
>
> --
> Iñaki Baz Castillo
>
>

array1 & array2

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