-1

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
Andrei
  • 1,121
  • 8
  • 19

2 Answers2

3

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)
mikej
  • 65,295
  • 17
  • 152
  • 131
1

When you use array_1 - array_2 may give inappropriate results in your case,

Suppose you have,

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

So in your case, you need to use the following

difference_1 = array_1.map.with_index { |v, i| v-array_2[i] }
difference_2 = array_2.map.with_index { |v, i| v-array_1[i] }

If you want to add it as a method

def find_difference(array_1, array_2)
  difference_1 = array_1.map.with_index { |v, i| v-array_2[i] }
  difference_2 = array_2.map.with_index { |v, i| v-array_1[i] }
  return [difference_1, difference_2]
end

You can call,

difference_array = find_difference(array_1, array_2)
Karthik P R
  • 134
  • 5