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

RubyIrb

Ruby Problem Overview


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.

Ruby Solutions


Solution 1 - Ruby

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 - Ruby

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 - Ruby

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 - Ruby

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 - Ruby

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionneezerView Question on Stackoverflow
Solution 1 - RubydmondarkView Answer on Stackoverflow
Solution 2 - RubyEthanView Answer on Stackoverflow
Solution 3 - RubyChrisView Answer on Stackoverflow
Solution 4 - RubyGdeglinView Answer on Stackoverflow
Solution 5 - RubyjacobsimeonView Answer on Stackoverflow