How to return the string representation of a hash in Ruby

Overview

The inspect method can be used to get the string representation of a hash in Ruby.

Syntax

hash.inspect

Parameters

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

Return value

The value returned is a string representation of the hash.

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"}
# print hash vales and type before string representation
puts "Before Getting String representation\n"
puts "h1 :\n Value = #{h1}, Type: #{h1.class} "
puts "h2 :\n Value = #{h2}, Type: #{h2.class} "
puts "h3 :\n Value = #{h3}, Type: #{h3.class} "
puts "h4 :\n Value = #{h4}, Type: #{h4.class} \n"
# get string representations
str1 = h1.inspect
str2 = h2.inspect
str3 = h3.inspect
str4 = h4.inspect
# print string representations and type
puts "String representation\n"
puts "Before Getting String representation\n"
puts "h1 :\n Value = #{str1}, Type: #{str1.class} "
puts "h2 :\n Value = #{str2}, Type: #{str2.class} "
puts "h3 :\n Value = #{str3}, Type: #{str3.class} "
puts "h4 :\n Value = #{str4}, Type: #{str4.class} \n"

Explanation

  • Lines 2-5: We create the hashes.

  • Lines 9-12: We print the hashes to the console along with their object type.

  • Lines 15 to 18: We get the string representations of the hashes using the inspect method.

  • Lines 23 to 26: We print the string representations of the hashes to the console along with their object types.

Free Resources