4

我想知道如何创建一个充满字符串的 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 或摘要只处理字符串,但我必须始终对数组进行排序并加入它才能使其正常工作。

那么有没有更好的呢?

4

4 回答 4

5

您可以将数组转换为 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
于 2012-10-19T08:21:53.113 回答
3

您可以对数组进行排序,将所有元素连接到一个字符串并对其进行哈希处理。

def hash(array)
   Digest::SHA1.digest(array.join)
end
于 2012-10-19T08:19:02.820 回答
0

已经有一个称为该类的标准setSet。您也可以轻松地自己实现它。而不是这样的数组:

["a", "b", "c", "d"]

将其保留为哈希:

{"a" => true, "b" => true, "c" => true, "d" => true}
于 2012-10-19T08:21:03.123 回答
0

似乎.hash忽略了无状态的方面。运行以下方面此问题的时间敏感性:

a = %w(alpha bravo charlie delta echo foxtrot gulf hotel india july kilo sheep)
c = %w(alpha bravo charlie delta echo foxtrot gulf hotel india july kilo sheep)

require 'ap'

ap a
ap c

def h2(value)
    Digest::SHA512.hexdigest value.inspect
end

aa = h2(a)
cc = h2(c)
ap aa
ap cc

ap "they are equal" if aa==cc
puts

t = Turtle.new("Tom", "blue")  # an object with two ivars, name and colour
ap h2(t)

t.name = "Teth"
ap h2(t)

t.name = "Tom"
ap h2(t)
puts

t.colour = "ruby red"
ap h2(t)

t.colour = "blue"
ap h2(t)
于 2019-01-20T14:37:01.727 回答