2013-08-17 15 views
9

Bu, Ruby equivalent of Perl Data::Dumper kopyası değil. Bu soru 3.5 yaşından büyüktür ve bu nedenle kontrol etmek istediğinizde o zamandan beri Ruby'de yeni seçenekler mevcut.Derin iç içe geçmiş kümeleri/dizileri basmak için perl'in "Data :: Dumper" Ruby'si eşdeğeri

Perl'in Ruby'de Dumper eşdeğerini arıyorum. Dumper'ın perde arkasında ne yaptığını umursamıyorum. Perl derin iç içe hashlar ve dizi yazdırmak için yaygın olarak kullandım. Şu ana kadar yakutta bir alternatif bulamadım (ya da Ruby'de mevcut alternatifleri iyi kullanmak için bir yol bulamadım).

Bu benim Perl kodları ve Çıktı geçerli:

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

ÇIKIŞ:

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

Sadece Damper seviyorum. Ruby'de pp, p, inspect ve yaml çalıştı.

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

ÇIKIŞ:

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

Teşekkür burada yakut ve çıkışında benim aynı kodudur.

+0

ne yaml bu test kodu için iyidir * demek ama gerçekten derin iç içe yapılar için do * ? –

+3

yaml çıktısı, derin karmalar/diziler söz konusu olduğunda, Damper ile karşılaştırıldığında okumak ve yorumlamak için acı vericidir (benim için en azından). – slayedbylucifer

+0

downvotes? ne için? sorunun nesi var? – slayedbylucifer

cevap

9

Ne Awesome Print hakkında: (aslında dizim)

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

Çıktı:

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

Aah, awesome_print gerçekten harika. Teşekkürler @Stefan – slayedbylucifer