我有一个大哈希嵌套数组和哈希。我想简单地打印出来,所以它'可读'的用户。

我希望它有点像to_yaml -这是相当可读的-但仍然太高科技看起来。

最终需要读取这些数据块的将是最终用户,因此它们需要被清晰地格式化。

有什么建议吗?


当前回答

在我尝试的所有宝石中,show_data宝石对我来说工作得最好,我现在广泛地使用它来记录Rails中的参数散列

其他回答

在我尝试的所有宝石中,show_data宝石对我来说工作得最好,我现在广泛地使用它来记录Rails中的参数散列

另一个解决方案比pp或awesome_print更适合我:

require 'pry' # must install the gem... but you ALWAYS want pry installed anyways
Pry::ColorPrinter.pp(obj)

如果要打印给用户,请使用上面的答案。

如果你只想在控制台为自己打印,我建议使用撬宝石而不是irb。除了漂亮的印刷,撬还有很多其他功能(查看下面的railscast)

宝石安装撬

看看这个铁路广播:

http://railscasts.com/episodes/280-pry-with-rails

下面是使用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))))

(解析来自RestClient的响应)

对于大型嵌套散列,此脚本可能对您有帮助。它以类似python的漂亮语法打印嵌套散列,仅缩进以方便复制。

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

使用示例:

  h = {a: { b: { c: :d }, e: :f }, g: :i }
  PrettyHash.call(h)

a:
  b:
    c: d
  e: f
g: i
=> 3

返回值是嵌套散列的所有结束级值的计数(3)。