Find values in common between two arrays

后端 未结 3 1665
北海茫月
北海茫月 2021-01-30 10:52

If I want to compare two arrays and create an interpolated output string if an array variable from array y exists in x how can I get an output for each

相关标签:
3条回答
  • 2021-01-30 11:07

    You can use the set intersection method & for that:

    x = [1, 2, 4]
    y = [5, 2, 4]
    x & y # => [2, 4]
    
    0 讨论(0)
  • 2021-01-30 11:09
    x = [1, 2, 4]
    y = [5, 2, 4]
    intersection = (x & y)
    num = intersection.length
    puts "There are #{num} numbers common in both arrays. Numbers are #{intersection}"
    

    Will output:

    There are 2 numbers common in both arrays. Numbers are [2, 4]
    
    0 讨论(0)
  • 2021-01-30 11:20

    OK, so the & operator appears to be the only thing you need to do to get this answer.

    But before I knew that I wrote a quick monkey patch to the array class to do this:

    class Array
      def self.shared(a1, a2)
        utf = a1 - a2 #utf stands for 'unique to first', i.e. unique to a1 set (not in a2)
        a1 - utf
      end
    end
    

    The & operator is the correct answer here though. More elegant.

    0 讨论(0)
提交回复
热议问题