17

I am learning Ruby & Perl has this very convenient module called Data::Dumper, which allows you to recursively analyze a data structure (like hash) & allow you to print it. This is very useful while debugging. Is there some thing similar for Ruby?

John
  • 1,681
  • 3
  • 20
  • 28

3 Answers3

19

Look into pp

example:

  require 'pp'
  x = { :a => [1,2,3, {:foo => bar}]}
  pp x

there is also the inspect method which also works quite nicely

  x = { :a => [1,2,3, {:foo => bar}]}
  puts x.inspect
Daniel
  • 4,847
  • 1
  • 23
  • 19
3

I normally use a YAML dump if I need to quickly check something.

In irb the syntax is simply y obj_to_inspect. In a normal Ruby app, you may need to add a require 'YAML' to the file, not sure.

Here is an example in irb:

>> my_hash = {:array => [0,2,5,6], :sub_hash => {:a => 1, :b => 2}, :visible => true}
=> {:sub_hash=>{:b=>2, :a=>1}, :visible=>true, :array=>[0, 2, 5, 6]}
>> y my_hash  # <----- THE IMPORTANT LINE
--- 
:sub_hash: 
  :b: 2
  :a: 1
:visible: true
:array: 
- 0
- 2
- 5
- 6
=> nil
>> 

The final => nil just means the method didn't return anything. It has nothing to do with your data structure.

Doug Neiner
  • 65,509
  • 13
  • 109
  • 118
2

you can use Marshal, amarshal, YAML

ghostdog74
  • 327,991
  • 56
  • 259
  • 343