Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does ruby's String .hash method work?

Tags:

ruby

hash

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 ?

like image 464
Ye Lin Aung Avatar asked Mar 24 '10 06:03

Ye Lin Aung


2 Answers

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.

like image 164
Marcel Jackwerth Avatar answered Oct 02 '22 01:10

Marcel Jackwerth


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'"
like image 42
lacostenycoder Avatar answered Oct 02 '22 02:10

lacostenycoder