Friday, February 11, 2011

Makandra - Comparing two arrays

I recently came across a website called makandra.com. They have notes publicly available that they would normally only use internally. One not caught my eye, Check if two arrays contain the same elements with and without RSpec. The code for RSpec is straight-forward and simple but the code to duplicate that functionality is somewhat more than is needed. This function:

def difference_between_arrays(array1, array2)
  difference = array1.dup
  array2.each do |element|
    if index = difference.index(element)
      difference.delete_at(index)
    end
  end
  difference
end

could go away completely without any problem. Without this function, the second could be re-written like this and achieve the exact same functionality:

def same_elements?(array1, array2)
  extra_items = array1 - array2
  missing_items = array2 - array1
  extra_items.empty? & missing_items.empty?
end

I'm not sure if Henning Koch will come across this or not, but maybe it'll help him out (or anyone else that comes across this).

No comments:

Post a Comment