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

57,438

Solution 1

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

Solution 2

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

Solution 3

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!

Solution 4

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"}

Solution 5

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"]} 
Share:
57,438
neezer
Author by

neezer

Gotta love learning!

Updated on July 05, 2022

Comments

  • neezer
    neezer almost 2 years

    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.

  • Nedunchezhian A
    Nedunchezhian A almost 15 years
    Nice one, didn't know it (I just love YAML)
  • taw
    taw over 13 years
    pp buys you indentation if object is too big.
  • aenw
    aenw over 10 years
    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.
  • Adam Marshall
    Adam Marshall over 10 years
    I like this one, nice looking Hashes!