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

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

这不是与PerlData::Dumper相当的Ruby的副本。这个问题已经有3.5年的历史了,所以想检查Ruby是否有新的选项。

我在寻找Perl的Dumper在Ruby中的等价物。我不在乎翻斗车在窗帘后面做什么。我广泛地使用它来打印Perl中的深层嵌套散列和数组。到目前为止,我还没有在Ruby中找到一个替代品(或者我可能还没有找到一种方法来充分利用Ruby中可用的替代品)。

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

1
2
3
4
5
6
7
8
9
10
11
12
#!/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);

输出:

1
2
3
4
5
6
7
8
9
10
$VAR1 = {
          'what' => {
                      'who' => 'you',
                      'where' => 'me'
                    },
          'which' => {
                       'why' => 'him',
                       'whom' => 'she'
                     }
        };

喜欢垃圾车。:)

在鲁比,我试过pppinspectyaml。下面是我在Ruby中的相同代码及其输出:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#!/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"

输出:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
{: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
2
3
require 'awesome_print'
hash = {what: {where:"me", who:"you"}, which: { whom:"she", why:"him"}}
ap hash

输出(实际上带有语法突出显示):

1
2
3
4
5
6
7
8
9
10
{
     :what => {
        :where =>"me",
          :who =>"you"
    },
    :which => {
        :whom =>"she",
         :why =>"him"
    }
}