【问题标题】:Inspecting a hash检查哈希
【发布时间】:2013-01-11 10:24:28
【问题描述】:

当我想调试以下哈希时,它返回try2test2

dictionary = {
  "test" => 2,
  "try" => 2
}

puts dictionary
# => try2test2

有没有其他方法可以为您提供完整的列表,如{'test': 2, 'try': 2}

【问题讨论】:

  • 你试过dictionary.inspect吗?
  • 您使用的是哪个 ruby​​ 版本? Hash#to_s 不应像 try2test2 一样返回。
  • dictionary.inspect 有效!非常感谢!

标签: ruby hash inspect


【解决方案1】:

正如 V. Melnychuk 所说,JSON 是一个不错的选择,只要记住先导入“json”模块即可:

require "json"
dictionary.to_json

通常,您可以通过调用来检索对象的可读字符串版本 检查它:

dictionary.inspect

最后,有一个“pp”模块可以漂亮地打印变量(很像 python 中的 pprint 模块):

require "pp"
pp dictionary

希望对你有帮助!

【讨论】:

  • 谢谢,我忘了导入模块
【解决方案2】:

尝试将对象转换为 JSON

dictionary.to_json

【讨论】:

    【解决方案3】:

    你也可以p dictionary 默认发送inspect

    dictionary = {
      "test" => 2,
      "try" => 2
    }
    
    p dictionary      # => {"test"=>2, "try"=>2}
    

    【讨论】:

      猜你喜欢
      • 2011-12-28
      • 2017-04-28
      • 2013-07-20
      • 2011-05-19
      • 1970-01-01
      • 2014-12-09
      • 2012-09-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多