Ruby 1.8和1.9的字符串是否有相同的散列码? [英] Do Ruby 1.8 and 1.9 have the same hash code for a string?

查看:94
本文介绍了Ruby 1.8和1.9的字符串是否有相同的散列码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 String.hash 来生成哈希码,但我担心如果一段时间后我将版本从1.8升级到1.9,哈希生成的代码也会发生变化。

Ruby 1.8和1.9的字符串是否具有相同的哈希码?

解决方案

幸运的是,答案很简单,因为它们不会:

 〜$ ruby​​1.8 -e'phello world.hash'
444332266
〜$ ruby​​1.9 -e'phello world.hash '
-194819219

如果你使用内建的散列方法,我会建议有一个脚本作为生成必要的哈希码的构建过程的一部分。请注意,即使从一台机器到下一台机器,它们也不能保证是相同的。



如果您需要一致的散列,请使用 CRC32 SHA1

 >>需要'zlib'
>> Zlib.crc32hello world
=> 222957957
>>需要'摘要'
>> Digest :: SHA1.hexdigesthello world
=> 2aae6c35c94fcfb415dbe95f408b9ce91ee846ed
>> Digest :: MD5.hexdigesthello world
=> 5eb63bbbe01eeed093cb22bb8f5acdc3

它们有很不同的用途,但CRC32的优点是返回一个32位数而且速度相当快,而SHA1是80位数字,但更安全。 (我假设这不是用于加密的目的,但是如果你需要的话,可以查看SHA-256。)


I want to use String.hash to generate the hash code, but I'm worried that if some time later I upgrade the version from 1.8 to 1.9, the hash code generated will also change.

Do Ruby 1.8 and 1.9 have the same hash code for a string?

解决方案

Fortunately, the answer is easy because they do not:

~$ ruby1.8 -e 'p "hello world".hash'
444332266
~$ ruby1.9 -e 'p "hello world".hash'
-194819219

If you use the builtin hash method, I would recommend having a script as part of your build process that generates the necessary hashcodes. Note that they are not guaranteed to be the same even from one machine to the next.

If you need consistent hashing, use something like CRC32 or SHA1:

>> require 'zlib'
>> Zlib.crc32 "hello world"
=> 222957957
>> require 'digest'
>> Digest::SHA1.hexdigest "hello world"
=> "2aae6c35c94fcfb415dbe95f408b9ce91ee846ed"
>> Digest::MD5.hexdigest "hello world"
=> "5eb63bbbe01eeed093cb22bb8f5acdc3"

They have quite different purposes, but CRC32 has the advantage of returning a 32-bit number and being quite fast, while SHA1 is an 80-bit number but more secure. (I’m assuming this is not for cryptographic purposes, but look into SHA-256 if you need it.)

这篇关于Ruby 1.8和1.9的字符串是否有相同的散列码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆