【问题标题】:Ruby on Rails: pretty print for variable.hash_set.inspect ... is there a way to pretty print .inpsect in the console?Ruby on Rails:variable.hash_set.inspect 的漂亮打印...有没有办法在控制台中漂亮地打印 .inpsect?
【发布时间】:2011-09-29 15:42:19
【问题描述】:

我发现自己在我的功能测试中做了很多 puts .inpsect 来确保我知道数据是如何格式化的......但是当哈希对象中的每个条目之后没有新行时,哈希很难阅读. 无论如何,也许是一个宝石?,漂亮地打印哈希?

所以它看起来像这样:

{ 
  entry1 => { 
              entrey1.1 => 1,
              entry1.2 => 3
            },
  entry2 => 3
}

而不是:{ entry1 => { entrey1.1 => 1, entry1.2 => 3}, entry2 => 3 } ?

谢谢!

【问题讨论】:

    标签: ruby-on-rails ruby console


    【解决方案1】:

    您可以为此使用 awesome_print gem。

    https://github.com/michaeldv/awesome_print

    require 'awesome_print' # if you like to have it in irb by default, add it to your irbrc
    >> ap({:a => 1, :b => [1,2,3], :c => :d})
    {
        :b => [
            [0] 1,
            [1] 2,
            [2] 3
        ],
        :a => 1,
        :c => :d
    }
    

    顺便说一句,您也可以只使用p object 而不是puts object.inspect,它会在打印之前在对象中调用inspect。 另一种打印对象比默认 puts 更好的方法是使用 ruby​​ 标准库中的 pp (http://ruby-doc.org/stdlib/libdoc/pp/rdoc/index.html)

    【讨论】:

    • ap 很好,但是 1.0.2 不能很好地显示 html - 一种解决方法是在 css 中设置 pre {display:inline}
    • pp 很棒(无需安装 gem 即可快速解决)
    • 我们可以用require 'ap' 代替require 'awesome_print'
    【解决方案2】:

    如果您愿意,您可以随时在您的.irbrc 文件中重新定义Hash#inspect,将它们格式化为您想要的任何格式。这只会影响您的交互环境。另一种方法是将它们表示为通常更具可读性的 YAML。例如:

    def y(object)
      puts object.to_yaml
      return
    end
    

    这样您就可以像今天的p 一样在对象上运行y

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-05-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-16
      • 2021-08-19
      • 1970-01-01
      相关资源
      最近更新 更多