Search code examples
ruby-on-railsrubycomputer-science

Finding the differences in 2 arrays


Is there a more elegant way of accomplishing the following in Ruby?

array_1 = [1,2,3]
array_2 = [3,4,5]

(array_1 - array_2).each do |num|
  some_method_z(num)
end

(array_2 - array_1).each do |num|
  some_method_x(num)
end

For example-- would love to be able to do something like:

difference_1, difference_2 = ruby_method(array_1, array_2)

which would be the equivalent to:

difference_1 = array_1 - array_2
difference_2 = array_2 - array_1

Solution

  • You could write your own method along the lines of:

    def ruby_method(array_1, array_2)
      [array_1 - array_2, array_2 - array_1]
    end
    

    This would return an array with the 2 differences, but you can unpack this into 2 separate variables on the left hand side of the call in exactly the way you mentioned:

    difference_1, difference_2 = ruby_method(array_1, array_2)