Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby equivalent of perl's "Data::Dumper" for printing deep nested hashes/arrays

Tags:

ruby

perl

This is not a duplicate of Ruby equivalent of Perl Data::Dumper. That question is more than 3.5 years old and hence want to check are there any new options available in Ruby since then.

I am looking for perl's Dumper equivalent in ruby. I don't care what Dumper does behind the curtains. I have used it extensively for printing deep nested hashes and array in perl. So far I haven't found an alternative in ruby (Or I may not have find a way to make good use of available alternatives in Ruby).

This is my perl code and its Output:

#!/usr/bin/perl -w
use strict;
use Data::Dumper;

my $hash;

$hash->{what}->{where} = "me";
$hash->{what}->{who} = "you";
$hash->{which}->{whom} = "she";
$hash->{which}->{why} = "him";

print Dumper($hash);

OUTPUT:

$VAR1 = {
          'what' => {
                      'who' => 'you',
                      'where' => 'me'
                    },
          'which' => {
                       'why' => 'him',
                       'whom' => 'she'
                     }
        };

Just Love the Dumper. :)

In ruby, I tried pp, p, inspect and yaml. here is my same code in ruby and its output:

#!/usr/bin/ruby
require "pp"
require "yaml"
hash = Hash.new{ |h,k| h[k] = Hash.new(&h.default_proc) }

hash[:what][:where] = "me"
hash[:what][:who] = "you"
hash[:which][:whom] = "she"
hash[:which][:why] = "him"

pp(hash)
puts "Double p did not help. Lets try single p"
p(hash)
puts "Single p did not help either...lets do an inspect"
puts hash.inspect
puts "inspect was no better...what about yaml...check it out"
y hash
puts "yaml is good for this test code but not for really deep nested structures"

OUTPUT:

{:what=>{:where=>"me", :who=>"you"}, :which=>{:whom=>"she", :why=>"him"}}
Double p did not help. Lets try single p
{:what=>{:where=>"me", :who=>"you"}, :which=>{:whom=>"she", :why=>"him"}}
Single p did not help either...lets do an inspect
{:what=>{:where=>"me", :who=>"you"}, :which=>{:whom=>"she", :why=>"him"}}
inspect was no better...what about yaml...check it out
--- 
:what: 
  :where: me
  :who: you
:which: 
  :whom: she
  :why: him
yaml is good for this test code but not for really deep nested structures

Thanks.

like image 761
slayedbylucifer Avatar asked Aug 17 '13 19:08

slayedbylucifer


1 Answers

What about Awesome Print:

require 'awesome_print'
hash = {what: {where: "me", who: "you"}, which: { whom: "she", why: "him"}}
ap hash

Output (actually with syntax highlighting):

{
     :what => {
        :where => "me",
          :who => "you"
    },
    :which => {
        :whom => "she",
         :why => "him"
    }
}
like image 91
Stefan Avatar answered Nov 04 '22 05:11

Stefan