如何创建ruby数组的一致哈希字符串?

时间:2012-10-19 08:09:50

标签: 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

Zlib或digest只做字符串,但我必须总是对数组进行排序并加入它以使其正常工作。

那还有什么更好的吗?

4 个答案:

答案 0 :(得分:5)

您可以将数组转换为Set并调用to_set方法(不要忘记'require'步骤>

a = ["a", "b", "c", "d"]
a.to_set.hash # => 425494174200536878

b = ["d", "b", "c", "a"]
b.to_set.hash # => 425494174200536878

答案 1 :(得分:3)

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

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

答案 2 :(得分:0)

已经有一个名为set的标准库引入了Set类。您也可以自己轻松实现它。而不是像这样的数组:

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

将其保留为哈希:

{"a" => true, "b" => true, "c" => true, "d" => true}

答案 3 :(得分: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)