Created
February 21, 2011 16:24
-
-
Save dkln/837288 to your computer and use it in GitHub Desktop.
Diff's two hashes with eachother
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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