Search code examples
rubyarrayshashzlibdigest

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?


Solution

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

    def hash(array)
       Digest::SHA1.digest(array.join)
    end