Ruby相当于perl的“Data :: Dumper”,用于打印深层嵌套的哈希/数组

时间:2013-08-17 19:26:31

标签: ruby perl

这不是Ruby equivalent of Perl Data::Dumper的重复。这个问题已超过3。5年了,因此想要检查从那时起Ruby中是否有任何新选项。

我正在寻找红宝石中perl的Dumper等价物。我不在乎翻车机幕后做什么。我已经广泛使用它在perl中打印深嵌套哈希和数组。到目前为止,我还没有在ruby中找到替代方案(或者我可能没有找到一种方法来充分利用Ruby中的可用替代方案)。

这是我的perl代码及其输出:

#!/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);

输出:

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

只是喜欢翻车机。 :)

在ruby中,我尝试了pppinspectyaml。这是我在ruby中的相同代码及其输出:

#!/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"

输出:

{: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

感谢。

1 个答案:

答案 0 :(得分:9)

Awesome Print

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

输出(实际上是语法高亮显示):

{
     :what => {
        :where => "me",
          :who => "you"
    },
    :which => {
        :whom => "she",
         :why => "him"
    }
}