ruby 漂亮打印散列的最佳方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8842546/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Best way to pretty print a hash
提问by Adam O'Connor
I have a large hash with nested arrays and hashes. I would like to simply print it out so it 'readable' to the user.
我有一个带有嵌套数组和散列的大散列。我想简单地将其打印出来,以便用户“可读”。
I would like it to be sort of like to_yaml - that's pretty readable - but still too tech looking.
我希望它有点像 to_yaml - 这很好读 - 但看起来仍然太技术化。
Ultimately its going to be end users who need to read these data chunks so they need to be formatted cleanly.
最终,最终用户将需要读取这些数据块,因此需要对其进行干净的格式化。
Any suggestions?
有什么建议?
回答by Phrogz
require 'pp'
pp my_hash
Use ppif you need a built-in solution and just want reasonable line breaks.
使用pp如果你需要一个内置的解决方案,只是想合理的换行符。
Use awesome_printif you can install a gem. (Depending on your users, you may wish to use the index:falseoption to turn off displaying array indices.)
如果您可以安装 gem,请使用awesome_print。(根据您的用户,您可能希望使用该index:false选项来关闭显示数组索引。)
回答by David J.
If you have JSON, I recommend JSON.pretty_generate(hash)because it is simpler than awesome_print, looks great in a pretag, and allows for easy copying from a web page. (See also: How can I "pretty" format my JSON output in Ruby on Rails?)
如果你有 JSON,我推荐JSON.pretty_generate(hash)它,因为它比awesome_print更简单,在pre标签中看起来很棒,并且允许从网页轻松复制。(另请参阅:如何在 Ruby on Rails 中“漂亮”格式化我的 JSON 输出?)
回答by Alex D
Another solution which works better for me than ppor awesome_print:
另一种比ppor更适合我的解决方案awesome_print:
require 'pry' # must install the gem... but you ALWAYS want pry installed anyways
Pry::ColorPrinter.pp(obj)
回答by Nick Schwaderer
If you don't have any fancy gem action, but do have JSON, this CLI line will work on a hash:
如果您没有任何花哨的 gem 操作,但有 JSON,则此 CLI 行将适用于散列:
puts JSON.pretty_generate(my_hash).gsub(":", " =>")
puts JSON.pretty_generate(my_hash).gsub(":", " =>")
#=>
{
:key1 => "value1",
:key2 => "value2",
:key3 => "value3"
}
回答by Abdo
Use the answers above if you're printing to users.
如果您要打印给用户,请使用上面的答案。
If you only want to print it for yourself in console, I suggest using the pry gem instead of irb. Besides pretty printing, pry has a lot of other features as well (check railscast below)
如果您只想在控制台中为自己打印,我建议使用 pry gem 而不是 irb。除了漂亮的打印外,pry 还具有许多其他功能(请查看下方的 railscast)
gem install pry
gem安装撬
And check this railscast:
并检查此 railscast:
回答by grosser
Easy to do with json if you trust your keys to be sane:
如果您相信您的密钥是理智的,那么使用 json 很容易:
JSON.pretty_generate(a: 1, 2 => 3, 3 => nil).
gsub(": null", ": nil").
gsub(/(^\s*)"([a-zA-Z][a-zA-Z\d_]*)":/, "\1\2:"). # "foo": 1 -> foo: 1
gsub(/(^\s*)(".*?"):/, "\1\2 =>") # "123": 1 -> "123" => 1
{
a: 1,
"2" => 3,
"3" => nil
}
回答by bartoindahouse
Using Pry you just need to add the following code to your ~/.pryrc:
使用 Pry,您只需将以下代码添加到您的 ~/.pryrc 中:
require "awesome_print"
AwesomePrint.pry!
回答by Dr.Strangelove
Of all the gems I tried, show_datagem worked the best for me, I now use it extensively to log params hash in Rails pretty much all the time
在我尝试过的所有 gem 中,show_datagem 对我来说效果最好,我现在几乎一直广泛使用它来记录 Rails 中的参数哈希
回答by swilgosz
For large nested hashes this script could be helpful for you. It prints a nested hash in a nice python/like syntax with only indents to make it easy to copy.
对于大型嵌套散列,此脚本可能对您有所帮助。它以漂亮的 python/like 语法打印嵌套哈希,只有缩进,以便于复制。
module PrettyHash
# Usage: PrettyHash.call(nested_hash)
# Prints the nested hash in the easy to look on format
# Returns the amount of all values in the nested hash
def self.call(hash, level: 0, indent: 2)
unique_values_count = 0
hash.each do |k, v|
(level * indent).times { print ' ' }
print "#{k}:"
if v.is_a?(Hash)
puts
unique_values_count += call(v, level: level + 1, indent: indent)
else
puts " #{v}"
unique_values_count += 1
end
end
unique_values_count
end
end
Example usage:
用法示例:
h = {a: { b: { c: :d }, e: :f }, g: :i }
PrettyHash.call(h)
a:
b:
c: d
e: f
g: i
=> 3
The returned value is the count (3) of all the end-level values of the nested hash.
返回值是嵌套散列的所有最终级值的计数 (3)。
回答by Adobe
Here's another approach using json and rouge:
这是使用 json 和 rouge 的另一种方法:
require 'json'
require 'rouge'
formatter = Rouge::Formatters::Terminal256.new
json_lexer = Rouge::Lexers::JSON.new
puts formatter.format(json_lexer.lex(JSON.pretty_generate(JSON.parse(response))))
(parses response from e.g. RestClient)
(解析来自 eg 的响应RestClient)

