Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby equivalent of Perl Data::Dumper

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?

like image 604
John Avatar asked Jan 29 '10 02:01

John


3 Answers

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
like image 82
Daniel Avatar answered Oct 01 '22 12:10

Daniel


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.

like image 37
Doug Neiner Avatar answered Oct 01 '22 12:10

Doug Neiner


you can use Marshal, amarshal, YAML

like image 24
ghostdog74 Avatar answered Oct 01 '22 10:10

ghostdog74