Ruby: How to make IRB print structure for Arrays and Hashes
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
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
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!