Ye Lin Aung
Ye Lin Aung

Reputation: 11469

How does ruby's String .hash method work?

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 ?

Upvotes: 10

Views: 9198

Answers (2)

lacostenycoder
lacostenycoder

Reputation: 11226

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'"

Upvotes: 5

Marcel Jackwerth
Marcel Jackwerth

Reputation: 54782

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.

Upvotes: 11

Related Questions