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

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

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

有什么建议吗?


当前回答

在Rails中,Ruby中的数组和哈希有内置的to_json函数。我会使用JSON,因为它在web浏览器中是非常可读的,例如谷歌Chrome。

也就是说,如果你担心它看起来太“科技”,你可能应该写自己的函数,用空格和其他字符替换散列和数组中的花括号和方括号。

在gsub函数中找到一个很好的方法。继续使用不同的字符和不同数量的空白,直到你找到一些看起来有吸引力的东西。http://ruby-doc.org/core-1.9.3/String.html#method-i-gsub

其他回答

对于大型嵌套散列,此脚本可能对您有帮助。它以类似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)。

如果你没有任何花哨的宝石操作,但有JSON,这个CLI行将适用于哈希:

把JSON.pretty_generate (my_hash)。Gsub (":", " =>")

#=>
{
  :key1 => "value1",

  :key2 => "value2",

  :key3 => "value3"
}

使用Pry,你只需要添加以下代码到你的~/.pryrc:

require "awesome_print"
AwesomePrint.pry!

如果你相信你的键是正常的,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
}

如果你有JSON,我推荐JSON.pretty_generate(散列),因为它比awesome_print更简单,在pre标签中看起来很棒,并且允许轻松地从网页复制。(请参见:如何在Ruby on Rails中“漂亮”地格式化JSON输出?)