Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are my hashes printed as strings?

Tags:

ruby

It's pretty wierd, but I do not know what to configure or where to configure. I am trying to print a simple hash value as below:

#!/usr/bin/ruby

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

puts names

I expect the output to be

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

while I get

1Jane2Thomas

Any ideas?

like image 411
PCoder Avatar asked Aug 08 '12 09:08

PCoder


2 Answers

You should use inspect.

puts names.inspect
#=> {1=>"Jane", 2=>"Thomas"}
like image 78
oldergod Avatar answered Nov 10 '22 00:11

oldergod


The puts method calls to_s on its argument(s) and prints the result. The p method however calls inspect on its argument(s) and prints the result:

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

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

So, to have a nice Hash printout, either use

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

or

p {1=>"Jane", 2=>"Thomas"}
like image 22
severin Avatar answered Nov 10 '22 01:11

severin