10

これは、Perl Data::Dumper に相当する Rubyの複製ではありません。その質問は 3.5 年以上前のものであるため、Ruby でそれ以降に利用できる新しいオプションがあるかどうかを確認したいと考えています。

Dumperrubyで perl に相当するものを探しています。カーテンの後ろでダンパーが何をしようと気にしない。私はこれを、深くネストされたハッシュと配列を 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'
                     }
        };

ダンパーが大好きです。:)

ppruby では、 、pinspectを試しyamlました。ルビーとその出力の私の同じコードは次のとおりです。

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

ありがとう。

4

1 に答える 1

9

素晴らしいプリントはどうですか:

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"
    }
}
于 2013-08-17T20:24:31.917 に答える