Ruby: How to make IRB print structure for Arrays and Hashes
Asked Answered
F

5

72

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.

Fellner answered 31/3, 2009 at 21:5 Comment(0)
A
122

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
Atrophy answered 31/3, 2009 at 21:12 Comment(1)
pp buys you indentation if object is too big.Expressage
N
61

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
Nowicki answered 15/7, 2009 at 0:57 Comment(2)
Nice one, didn't know it (I just love YAML)Blazonry
For 1.9 and later, instead of the y method , you should use YAML.dump. Per [github.com/tenderlove/psych/issues/50]: y polluted Kernel, and per [ruby-forum.com/topic/2332227], Kernel.y is private.Proclitic
A
16

The pretty print works well, but the Awesome_Print gem is even better! You will have to require awesome_print but it handles nested hashes and arrays beautifully plus colors them in the Terminal using 'ap' instead of 'p' to puts the output.

You can also include it in your ~/.irbrc to have this as the default method for displaying objects:

require "awesome_print"
AwesomePrint.irb!
Adage answered 20/2, 2012 at 14:43 Comment(1)
I like this one, nice looking Hashes!Iden
P
6

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"}
Pankey answered 31/3, 2009 at 21:12 Comment(0)
S
2

My personal tool of choice for this is 'Pretty Print' and the pp method

require 'pp' # <- 'Pretty Print' Included in ruby standard library
pp({ :hello => :world, :this => ['is', 'an', 'array'] })
=> {:hello=>:world, :this=>["is", "an", "array"]} 
Stimson answered 6/1, 2012 at 20:14 Comment(1)
It doesn't format more complex hashes at allDogwatch

© 2022 - 2024 — McMap. All rights reserved.