tags:

views:

751

answers:

3

When I make a new array/hash in irb, it prints out a nice format to show the structure, ex.

["value1", "value2", "value3"]
{"key1" => "value1"}

... but when I try to print out my variables using puts, I get them collapsed:

value1
value2
value3
key1
value1

I gather that puts is not the right command for what I want, but what is? I want to be able to view my variables in irb in the first format, not the second.

+10  A: 

You can either use the inspect method:

a=["value1", "value2", "value3"]
puts a.inspect

Or, even better, use the pp (pretty print) lib:

require 'pp'
a=["value1", "value2", "value3"]
pp a
dmondark
Perfect. Thanks!
neezer
what does pp buy you that p doesn't already give you?
rampion
One difference between them is that pp always return nil, while p return the object after printing it.
dmondark
`pp` buys you indentation if object is too big.
taw
+3  A: 

Try .inspect

>> a = ["value1", "value2", "value3"]
=> ["value1", "value2", "value3"]
>> a.inspect
=> "[\"value1\", \"value2\", \"value3\"]"
>> a = {"key1" => "value1"}
=> {"key1"=>"value1"}
>> a.inspect
=> "{\"key1\"=>\"value1\"}"

You can also use the p() method to print them:

>> p a
{"key1"=>"value1"}
Gdeglin
+2  A: 

Another thing you can do is use the y method which converts input into Yaml. That produces pretty nice output...

>> data = { 'dog' => 'Flemeale', 'horse' => 'Gregoire', 'cow' => 'Fleante' }
=> {"cow"=>"Fleante", "horse"=>"Gregoire", "dog"=>"Flemeale"}
>> y data
--- 
cow: Fleante
horse: Gregoire
dog: Flemeale
Ethan
Nice one, didn't know it (I just love YAML)
Yoann Le Touche
Of course, you have to `require yaml` to get the method.
Chuck