ChatGBPさんに教えてもらったコード
def compare_hashes_recursive(hash1, hash2)
added_keys = hash2.keys - hash1.keys
removed_keys = hash1.keys - hash2.keys
changed_keys = hash1.keys & hash2.keys
changes = changed_keys.each_with_object([]) do |key, result|
if hash1[key].is_a?(Hash) && hash2[key].is_a?(Hash)
nested_diff = compare_hashes_recursive(hash1[key], hash2[key])
result << { key => nested_diff } unless nested_diff.empty?
elsif hash1[key] != hash2[key]
result << { key => [hash1[key], hash2[key]] }
end
end
{
added: added_keys.map { |key| { key => hash2[key] } },
removed: removed_keys.map { |key| { key => hash1[key] } },
changed: changes
}.compact
end
ちゃんとテストはしていないため、参考までに、、、
コメント