What is the to_hash() method in Ruby?

Overview

The to_hash() method is a hash class method that returns the hash representation of the hash itself.

Syntax

Hash.to_hash()

Parameters

Hash: This is the hash whose hash representation we want to get.

Return value

Self object: This method returns the same hash.

Code example

# create hashes
h1 = {one: 1, two: 2, three: 3}
h2 = {name: "okwudili", stack: "ruby"}
h3 = {"foo": 0, "bar": 1}
h4 = {M:"Mango", A: "Apple", B: "Banana"}
# invoke to_hash() method
puts h1.to_hash()
puts h2.to_hash()
puts h3.to_hash()
puts h4.to_hash()

Code explanation

  • Lines 2–5: We create some hashes.
  • Lines 8–11: We invoke the to_hash() method on the hashes. Then, we print the results to the console.