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.
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"
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With