Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find matching values in ruby array?

Tags:

arrays

ruby

Have arrays [1, 2, 5] and [1, 2, 3] I would like to extract matching values, if there is a method like:

[1, 2, 5].match([1, 2, 3]) #=> [1, 2]

Is there any method on array, thank you

like image 656
Jackie Chan Avatar asked Nov 26 '12 03:11

Jackie Chan


1 Answers

Very simple:

[1,2,5] & [1,2,3]  #=> [1,2]

Other useful array operations include:

[1,2,3] | [1,3,4]  #=> [1,2,3,4]
[1,2,3] - [1,3,4]  #=> [2]
[1,2,3] + [1,3,4]  #=> [1,2,3,1,3,4]
like image 135
ray_linn Avatar answered Sep 18 '22 13:09

ray_linn