gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 06:49:59 25 4
gpt4 key购买 nike

这不是 Ruby equivalent of Perl Data::Dumper 的副本.这个问题已经超过 3.5 年了,因此想检查从那时起 Ruby 中是否有任何可用的新选项。

我正在寻找 perl 的 Dumper 在 ruby​​ 中的等价物。我不在乎 Dumper 在幕后做了什么。我已经广泛使用它在 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'
}
};

只爱自卸车。 :)

在 ruby​​ 中,我尝试了 pppinspectyaml。这是我在 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"

输出:

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

谢谢。

最佳答案

Awesome Print呢? :

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"
}
}

关于Ruby 相当于 perl 的 "Data::Dumper",用于打印深度嵌套的哈希/数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18292538/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com