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

2019-02-04 21:51发布

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?

标签: ruby hash
1条回答
Lonely孤独者°
2楼-- · 2019-02-04 22:13

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.)

查看更多
登录 后发表回答