How to get the hash value of a string in Ruby
Overview
We can get a hash value (integer value) of a string using the hash method. The hash values of two strings that are the same will also be the same.
Syntax
str.hash
Parameters
str: This is the string that calls the hash method. It is the string whose hash value we want.
Return value
The value returned is an integer that is the hash value of the string.
Code
# create some stringsstr1 = "Edpresso"str2 = "is"str3 = "great"# get the hash valuesa = str1.hashb = str2.hashc = str3.hash# print resultputs aputs bputs c
Explanation
-
In lines 2-4, we create a few string variables and initialize them with some values.
-
In lines 7-9, we call the
hashmethod on the strings created. -
In lines 12-14, we print the results.
As we can see when the code is run, we get the hash value of a string when the hash method is called on it.