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 strings
str1 = "Edpresso"
str2 = "is"
str3 = "great"
# get the hash values
a = str1.hash
b = str2.hash
c = str3.hash
# print result
puts a
puts b
puts 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 hash method 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.

Free Resources