How does ruby's String .hash method work?

2020-07-06 07:28发布

I'm just a newbie to ruby. I've seen a string method (String).hash .

For example, in irb, I've tried

>> "mgpyone".hash

returns

=> 144611910

how does this method works ?

标签: ruby hash
2条回答
劫难
2楼-- · 2020-07-06 07:55

If you need to get a consistent hashing output I would recommend NOT to use 'string.hash but instead consider using Digest::MD5 which will be safe in multi-instance cloud applications for example you can test this as mentioned in comment in previous by @BenCrowell

Run this 2x from your terminal, you will get different output each time:

ruby -e "puts 'a'.hash"

But if you run this the output will be consistent:

ruby -e "require 'digest'; puts Digest::MD5.hexdigest 'a'"
查看更多
啃猪蹄的小仙女
3楼-- · 2020-07-06 08:03

The hash method is defined for all objects. See documentation:

Generates a Fixnum hash value for this object. This function must have the property that a.eql?(b) implies a.hash == b.hash. The hash value is used by class Hash. Any hash value that exceeds the capacity of a Fixnum will be truncated before being used.

So the String.hash method is defined in C-Code. Basically (over-simplified) it just sums up the characters in that string.

查看更多
登录 后发表回答