Skip to content

Commit 54f78e0

Browse files
authored
add ability to compare deep within arrays (#9)
* add ability to compare deep within arrays * remove debug
1 parent 5be5104 commit 54f78e0

File tree

1 file changed

+21
-4
lines changed

1 file changed

+21
-4
lines changed

lib/hash_diff/comparison.rb

Lines changed: 21 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,13 @@ def comparison_strategy(reporter)
3434
end
3535

3636
def combined_keys
37-
(left.keys + right.keys).uniq
37+
if hash?(left) && hash?(right) then
38+
(left.keys + right.keys).uniq.sort
39+
elsif array?(left) && array?(right) then
40+
(0..[left.size, right.size].max).to_a
41+
else
42+
raise ArgumentError, "Don't know how to extract keys. Neither arrays nor hashes given"
43+
end
3844
end
3945

4046
def equal?(key)
@@ -45,13 +51,23 @@ def hash?(value)
4551
value.is_a?(Hash)
4652
end
4753

48-
def comparable?(key)
54+
def array?(value)
55+
value.is_a?(Array)
56+
end
57+
58+
def comparable_hash?(key)
4959
hash?(left[key]) && hash?(right[key])
5060
end
5161

62+
def comparable_array?(key)
63+
array?(left[key]) && array?(right[key])
64+
end
65+
5266
def report_difference(key, reporter)
53-
if comparable?(key)
67+
if comparable_hash?(key)
5468
self.class.new(left[key], right[key]).find_differences(&reporter)
69+
elsif comparable_array?(key)
70+
self.class.new(left[key], right[key]).find_differences(&reporter)
5571
else
5672
reporter.call(
5773
value_with_default(left, key),
@@ -61,7 +77,8 @@ def report_difference(key, reporter)
6177
end
6278

6379
def value_with_default(obj, key)
64-
obj.fetch(key, NO_VALUE)
80+
obj[key] || NO_VALUE
6581
end
6682
end
6783
end
84+

0 commit comments

Comments
 (0)