这不是Ruby等效于Perl Data :: Dumper的重复.这个问题已超过3.5年,因此想要检查从那时起Ruby中是否有任何新选项.
我在寻找perl Dumper在ruby中的等价物.我不在乎翻车机幕后做什么.我已经广泛使用它在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);
Run Code Online (Sandbox Code Playgroud)
OUTPUT:
$VAR1 = {
'what' => {
'who' => 'you',
'where' => 'me'
},
'which' => {
'why' => 'him',
'whom' => 'she'
}
};
Run Code Online (Sandbox Code Playgroud)
只是喜欢翻车机.:)
在Ruby中,我尝试了pp,p,inspect和yaml.这是我在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"
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
谢谢.
真棒打印怎么样:
require 'awesome_print'
hash = {what: {where: "me", who: "you"}, which: { whom: "she", why: "him"}}
ap hash
Run Code Online (Sandbox Code Playgroud)
输出(实际上是语法高亮):
{
:what => {
:where => "me",
:who => "you"
},
:which => {
:whom => "she",
:why => "him"
}
}
Run Code Online (Sandbox Code Playgroud)