我想知道如何为充满字符串的 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
Zlib 或 digest 只处理字符串,但我必须始终对数组进行排序并加入它才能使其正常工作。
那么有什么更好的吗?
最佳答案
您可以将数组转换为 Set 并调用 to_set
方法(不要忘记 `require 'set')
a = ["a", "b", "c", "d"]
a.to_set.hash # => 425494174200536878
b = ["d", "b", "c", "a"]
b.to_set.hash # => 425494174200536878
关于ruby - 如何创建 ruby 数组的一致哈希字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12969995/