Why are my hashes printed as strings?

This is rather strange, but I don’t know what to configure or where to configure. I am trying to print a simple hash value as shown below:

#!/usr/bin/ruby

names = Hash.new
names[1] = "Jane"
names[2] = "Thomas"

puts names

I expect the conclusion to be

{1=>"Jane", 2=>"Thomas"}

while i get

1Jane2Thomas

Any ideas?

+5
source share
2 answers

You must use validation.

puts names.inspect
#=> {1=>"Jane", 2=>"Thomas"}
+4
source

The puts method calls to_s in its arguments and prints the result. However, the p method calls to check on its arguments and prints the result:

{1=>"Jane", 2=>"Thomas"}.to_s
#=> '1Jane2Thomas'

{1=>"Jane", 2=>"Thomas"}.inspect
#=> '{1=>"Jane", 2=>"Thomas"}'

So, to have a beautiful Hash listing, use

puts {1=>"Jane", 2=>"Thomas"}.inspect

or

p {1=>"Jane", 2=>"Thomas"}
+3
source

All Articles