Ruby 相当于 perl 的“Data::Dumper"用于打印深度嵌套的散列/数组 [英] Ruby equivalent of perl's "Data::Dumper" for printing deep nested hashes/arrays
问题描述
这不是 Ruby 等效于 Perl Data::Dumper 的副本.这个问题已经有超过 3.5 年的历史了,因此想要检查从那时起 Ruby 中是否有任何可用的新选项.
This is not a duplicate of Ruby equivalent of Perl Data::Dumper. That question is more than 3.5 years old and hence want to check are there any new options available in Ruby since then.
我在 ruby 中寻找 perl 的 Dumper
等价物.我不在乎 Dumper 在幕后做了什么.我已经广泛地使用它在 perl 中打印深度嵌套的哈希和数组.到目前为止,我还没有在 ruby 中找到替代品(或者我可能没有找到一种方法来充分利用 Ruby 中的可用替代品).
I am looking for perl's Dumper
equivalent in ruby. I don't care what Dumper does behind the curtains. I have used it extensively for printing deep nested hashes and array in perl. So far I haven't found an alternative in ruby (Or I may not have find a way to make good use of available alternatives in Ruby).
这是我的 perl 代码及其输出:
This is my perl code and its Output:
#!/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 中,我尝试了 pp
、p
、inspect
和 yaml
.这是我在 ruby 中的相同代码及其输出:
In ruby, I tried pp
, p
, inspect
and yaml
. here is my same code in ruby and its output:
#!/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
谢谢.
推荐答案
require 'awesome_print'
hash = {what: {where: "me", who: "you"}, which: { whom: "she", why: "him"}}
ap hash
输出(实际上是语法高亮):
Output (actually with syntax highlighting):
{
:what => {
:where => "me",
:who => "you"
},
:which => {
:whom => "she",
:why => "him"
}
}
这篇关于Ruby 相当于 perl 的“Data::Dumper"用于打印深度嵌套的散列/数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!