I wonder how it is possible to create a consistent hash of a ruby array full of strings. The requirements are that the hash is always the same if the array contains the same values, independent of their order.
>> a = ["a", "b", "c", "d"]
>> SomeModule.hash(a)
=> "2aae6c35c94fcfb415dbe95f408b9ce91ee846ed"
>>
>> b = ["d", "b", "c", "a"]
>> SomeModule.hash(b)
=> "2aae6c35c94fcfb415dbe95f408b9ce91ee846ed"
>>
>> SomeModule.hash(a) == SomeModule.hash(b)
=> true
Zlib or digest only do strings, but I had to always sort the array and join it to get that working.
So is there anything better?
You can convert your array to Set and call to_set
method (don't foreget to `require 'set')
a = ["a", "b", "c", "d"]
a.to_set.hash # => 425494174200536878
b = ["d", "b", "c", "a"]
b.to_set.hash # => 425494174200536878
You can just sort the array, concatenate all elements to a string and hash it.
def hash(array)
Digest::SHA1.digest(array.join)
end
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