Skip to content

Instantly share code, notes, and snippets.

@dkln
Created February 21, 2011 16:24
Show Gist options
  • Save dkln/837288 to your computer and use it in GitHub Desktop.
Save dkln/837288 to your computer and use it in GitHub Desktop.
Diff's two hashes with eachother
def diff_hash(from, to)
differences = {}
to.each do |key, value|
if value.is_a? Hash
differences[key] = diff_hash_changed_items(from[key], value)
elsif value.is_a?(Array)
differences[key] = diff_array(value, from[key])
elsif from && from.has_key?(key) && value.to_s != from[key].to_s
differences[key] = [value, from[key]]
elsif !from || !from.has_key?(key)
differences[key] = [nil, value]
end
end
differences
end
def diff_array(from, to)
differences = []
to.each_with_index do |sub_value, index|
if from[index]
differences[index] = diff_hash_changed_items(from[index], sub_value)
else
differences[index] = diff_hash_changed_items(nil, sub_value)
end
end
differences
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment