1

Let's say I have an array like this one:

[
  [1, 2, 3, 4],
  [3, 4, 5, 6],
  [4, 5, 6, 8]
]

I need to get the elements in common between them all. How can I achieve that?

The result should be

 common_elements([[1, 2, 3, 4], [3, 4, 5, 6], [4, 5, 6, 8]]) # => [4]

2 Answers 2

4
[[1, 2, 3, 4], [3, 4, 5, 6], [4, 5, 6, 8]].reduce(:&) # => [4]

The Array#& method gives you set intersection:

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

The Enumerable#reduce method can combine the values in given array using an operation:

[1, 2, 3].reduce(:+) # => 6
Sign up to request clarification or add additional context in comments.

Comments

0

Here is another way of doing it "manually lol"... You do each to iterate of over the nested arrays [[0],[1],[2]], then you iterate over each nested array and use include ary[pos].include?(x) with AND between all three nested arrays to find intersecting value, It will be slow, but handy if you want to add more conditions .

 user> ary = [ [1,2,3,4], [3,4,5,6], [4,5,6,8] ]
 => [[1, 2, 3, 4], [3, 4, 5, 6], [4, 5, 6, 8]] 

user> ary.each { |f| f.each {|x| 
                 puts "#{x}"  if ary[0].include?(x) && ary[1].include?(x) &&  
                 ary[2].include?(x)  }} 
4
4
4

or simply,

2.1.2 :003 > ary = [ [1,2,3,4], [3,4,5,6], [4,5,6,8] ].inject(:&)
 => [4] 

3 Comments

Don't write code like [a=[1,2,3,4], b=[3,4,5,6], c=[4,5,6,8] ]. It's a maintenance nightmare and definitely not recommended or idiomatic.
I agree @ the Tin Man , I have changed the answer to not include the a=,b=,c= blah...
Now try to do it without using `include?' repeatedly. Imagine if the arrays increased to 100 times their size and the performance dropped to a crawl as a result.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.