Question

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.

Was it helpful?

Solution

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

OTHER TIPS

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!

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

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"]} 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top