Tho*_*ser 4 ruby arrays hash zlib digest
我想知道如何创建一个充满字符串的ruby数组的一致哈希.要求是,如果数组包含相同的值,则哈希值始终相同,与其顺序无关.
>> 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
Run Code Online (Sandbox Code Playgroud)
Zlib或digest只做字符串,但我必须总是对数组进行排序并加入它以使其正常工作.
那有什么更好的吗?
您可以将数组转换为Set和call to_set方法(不要预先设置为'require'set')
a = ["a", "b", "c", "d"]
a.to_set.hash # => 425494174200536878
b = ["d", "b", "c", "a"]
b.to_set.hash # => 425494174200536878
Run Code Online (Sandbox Code Playgroud)