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 ?
The hash
method is defined for all objects. See documentation:
Generates a
Fixnum
hash value for this object. This function must have the property thata.eql?(b)
impliesa.hash == b.hash
. The hash value is used by classHash
. Any hash value that exceeds the capacity of aFixnum
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.
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'"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With