10

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 ?

2 Answers 2

11

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.

Sign up to request clarification or add additional context in comments.

1 Comment

One thing to realize is that if you run a program more than once, the hashes change. That is, it's not just computing a hash based on the characters contained in the string. E.g., try doing ruby -e "print 'a'.hash" twice in a row. If you want a reproducible hash, you can use something like Digest::MD5.
6

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

1 Comment

The use cases for each are different. String#hash gives an int used for picking a hash bucket when storing a value in a Hash. MD5 was for giving objects a deterministic unique fingerprint. Since it returns a chunky string, not an int, it wouldn't be very useful for a hashmap data structure.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.