0

Possible Duplicate:
How to count duplicates in Ruby Arrays
Ruby: Compare 2 arrays for matches, and count the number of match instances

I am starting to using ruby language. Suppose I have two arrays:

a=["A", "B", "C", "D"]
b=["C", "A", "X", "Y", "F"]

I would like to count the number of duplicated elements of the two arrays. To achieve this, the idea I came up with is like following:

nr_of_duplicates = (a- (a - b)).size

Is there a better way to achieve this?

Community
  • 1
  • 1
Leem.fin
  • 40,781
  • 83
  • 202
  • 354
  • 1
    http://stackoverflow.com/questions/5013880/ruby-compare-2-arrays-for-matches-and-count-the-number-of-match-instances this might help u with the answer – Karan Shah Jan 23 '12 at 09:10
  • http://stackoverflow.com/questions/1765368/how-to-count-duplicates-in-ruby-arrays another one to achieve the same – Karan Shah Jan 23 '12 at 09:11
  • 1
    "This is more like a discussion than a question" is an _instant_ reason for closure. I'll get rid of it for you since this question is _not_ a discussion, it's looking for the best approach. – paxdiablo Jan 23 '12 at 09:13
  • If you are asking for a code-review, then the question should be on the code-review site: http://codereview.stackexchange.com/ – the Tin Man Jan 23 '12 at 09:16

1 Answers1

3

There is already a method defined in Array class for this called '&':

ary & other_ary → new_ary

Set Intersection—Returns a new array containing elements common to the two arrays, with no duplicates.

   [ 1, 1, 3, 5 ] & [ 1, 2, 3 ]   #=> [ 1, 3 ]
Syed Aslam
  • 8,707
  • 5
  • 40
  • 54