Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

ruby
communitycreator

What is array.hash() in Ruby?

okwudili onyejiaku

The hash() method returns the hash of an array. Arrays that are the same have the same hash.

Syntax

array.hash()

Parameter

The hash() method requires no parameter. It is only called on an array.

Return value

A hash is returned in this method.

# create Ruby arrays
array1 = [1, 2, 3, 4, 5]
array2 = ["a", "b", "c", "d", "e"]
array3 = ["Python", "Django", "Flask"]
array4 = [true, false, nil]
array5 = [["abc", "def"], 20, 30,40]

# get the hash of each array
a = array1.hash()   
b = array2.hash()   
c = array3.hash()   
d = array4.hash()     
e = array5.hash()   

# print the hash of each array
puts a
puts b
puts c
puts d
puts e

Arrays that are the same have the same hash. We can compare the hash values with the array.eql?() method. The array.eql?() method checks to see if two objects in Ruby are equal.

See the example below.

# Create equal arrays
array1 = [1, 2, 3, 4, 5]
array2 = [1, 2, 3, 4, 5]

# Create unequal arrays
array3 = ["a", "b", "c", "d", "e"]
array4 = [true, false, nil]

# compare the hash values
a = array1.hash().eql?(array2.hash())   # returns true

b = array2.hash().eql?(array3.hash())   # retunrs false

# print values
puts a 
puts b

RELATED TAGS

ruby
communitycreator
RELATED COURSES

View all Courses

Keep Exploring