我有一个看起来像这样的数据结构(Hash
):
{
foo: "Test string",
bar: [475934759, 5619827847]
}
我正在尝试从该 Hash
创建一个校验和,以在将来检查是否相等。我尝试使用 Hash
的 hash
方法,这导致了一个令人满意的好看的散列,但结果是相同的 Hash
会在解释器重新启动后生成不同的哈希值。
我真的只是希望能够从 Hash
、String
或 Array
实例创建一个 ~128 位校验和。
这可能吗?
最佳答案
您可以根据对象的 Marshal dump 计算自己的哈希值或 JSON代表。
这会计算 Marshal 转储的 MD5 哈希值:
require 'digest/md5'
hash = {
foo: "Test string",
bar: [475934759, 5619827847]
}
Marshal::dump(hash)
#=> "\x04\b{\a:\bfooI\"\x10Test string\x06:\x06ET:\bbar[\ai\x04'0^\x1Cl+\b\x87\xC4\xF7N\x01\x00"
Digest::MD5.hexdigest(Marshal::dump(hash))
#=> "1b6308abdd8f5f6290e2825a078a1a02"
更新
您可以实现自己的策略,但我不建议更改核心功能:
class Hash
def _dump(depth)
# this doesn't cause a recursion because sort returns an array
Marshal::dump(self.sort, depth)
end
def self._load(marshaled_hash)
Hash[Marshal::load(marshaled_hash)]
end
end
Marshal::dump({foo:1, bar:2})
#=> "\x04\bu:\tHash\e\x04\b[\a[\a:\bbari\a[\a:\bfooi\x06"
Marshal::dump({bar:2, foo:1})
#=> "\x04\bu:\tHash\e\x04\b[\a[\a:\bbari\a[\a:\bfooi\x06"
Marshal::load(Marshal::dump({foo:1, bar:2}))
#=> {:bar=>2, :foo=>1}
关于ruby - 有没有一种快速简便的方法可以从 Ruby 的基本数据结构创建校验和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19380370/