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.

neezer
  • 19,720
  • 33
  • 121
  • 220

5 Answers5

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
dmondark
  • 1,677
  • 1
  • 12
  • 19
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
Ethan
  • 57,819
  • 63
  • 187
  • 237
  • 1
    Nice one, didn't know it (I just love YAML) – Yoann Le Touche Jul 15 '09 at 01:04
  • 2
    For 1.9 and later, instead of the `y` method , you should use `YAML.dump`. Per [https://github.com/tenderlove/psych/issues/50]: `y` polluted Kernel, and per [https://www.ruby-forum.com/topic/2332227], `Kernel.y` is private. – aenw Sep 05 '13 at 10:47
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!
Chris
  • 11,819
  • 19
  • 91
  • 145
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"}
Gdeglin
  • 12,432
  • 5
  • 49
  • 65
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"]} 
jacobsimeon
  • 2,012
  • 1
  • 18
  • 20