Added :preserve_key_order option to maintain original hash key order#99
Merged
liufengyun merged 2 commits intoliufengyun:masterfrom May 20, 2025
Merged
Conversation
liufengyun
approved these changes
May 20, 2025
Owner
liufengyun
left a comment
There was a problem hiding this comment.
Thank you @robkiessling , LGTM 🎉
This file contains hidden or 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
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
This is in response to issue #98, which requests an option to preserve the original key order of compared hashes.
The existing implementation always outputs changes in a fixed order:
And within each group, keys are sorted alphabetically.
Unfortunately, this means that simply disabling
sort_byhere isn’t enough:hashdiff/lib/hashdiff/compare_hashes.rb
Lines 23 to 25 in b7734e3
because grouping by operation type still forces a reordering that doesn’t reflect the original hash structure.
My goal for this option is to have all deletions and updates listed in the order they appear in the first hash. Then, similar to how Ruby’s Hash#merge appends new keys, any keys found only in the second hash are appended in their original order.
To support this behavior, the logic for handling deletions, updates, and additions was unified into a
handle_keylambda. This allows each key to be evaluated in sequence, rather than processing all deletions, then all updates, then all additions in separate passes. I chose a lambda (instead of a separate method) to avoid having to pass in the many options and lookups needed within handle_key.