The inspect
method can be used to get the string representation of a hash in Ruby.
hash.inspect
Hash
: This is the hash we want to get the string representation of.
The value returned is a string representation of the hash.
# create hashesh1 = {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 representationputs "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 representationsstr1 = h1.inspectstr2 = h2.inspectstr3 = h3.inspectstr4 = h4.inspect# print string representations and typeputs "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"
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.