The code below is supposed to find the numbers in arr_1
that are missing in arr_2
.
def compare_1 (arr_1, arr_2)
output = []
temp = arr_2.each_with_object(Hash.new(0)) { |val, hsh| hsh[val] = 0 }
arr_1.each do |element|
if !temp.has_key? (element)
output << element
end
end
puts output
end
def compare_2 (arr_1, arr_2)
out = []
arr_1.each do |num|
if (!arr_2.include?(num))
out << num
end
end
puts out
end
According to 'benchmark', the first methods is faster, presumably by using hashes. Is there a neater way to write these or achieve this?
compare_1 times:
0.000000 0.000000 0.000000 ( 0.003001)
compare_2 times:
0.047000 0.000000 0.047000 ( 0.037002)
As SteveTurczyn said you could do
array_1 - array_2
Here is the definition of Array Difference
EDIT
Regarding performance, I made a benchmark by gathering the informations of this thread.