Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a consistent hashstring of a ruby array?

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?

like image 706
Thomas Fankhauser Avatar asked Feb 18 '23 19:02

Thomas Fankhauser


2 Answers

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
like image 156
Vasiliy Ermolovich Avatar answered Mar 03 '23 11:03

Vasiliy Ermolovich


You can just sort the array, concatenate all elements to a string and hash it.

def hash(array)
   Digest::SHA1.digest(array.join)
end
like image 26
iltempo Avatar answered Mar 03 '23 12:03

iltempo