I have a hash, for example:
filers = {query: 'nice post', sort: 'time_desc', post_type: 'blog'...limit: 100}
which is used to filter response data. I need to create a unique key for this hash to cache the response. I can think of taking its keys and values and converting them into a single string. Looking for some interesting answers that are simple and efficient.
Consider these following two steps:
Convert the Hash to a string (or other serialized format) after sorting the output write-order based on key.
It is important that the values are sorted by key during this transformation so that Hashes with the same key/value pairs (but with a different key order) will yield the same output. More complicated/nested structures need additional handling and should ensure consistent output for equivalent objects.
To get started with the process, consider:
sorted_kv_pairs = hash.to_a.sort_by {|k,v| k.to_s}
Use a hashing function such as SHA-1 or SHA-256/160 to generate a 40-byte Unique ID from the previously serialized object.
The huge output space (and cryptography qualities) of these functions make it unfeasible for there to be a purposeful collision and thus lead to "unique IDs".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With