How do I dump an object's fields to the console?

后端 未结 9 2257
谎友^
谎友^ 2020-12-12 10:09

When I\'m running a simple Ruby script, what\'s the easiest way to dump an object\'s fields to the console?

I\'m looking for something similar to PHP\'s print

相关标签:
9条回答
  • 2020-12-12 10:36

    puts foo.to_json

    might come in handy since the json module is loaded by default

    0 讨论(0)
  • 2020-12-12 10:39

    If you want to print an already indented JSON:

    require 'json'
    ...
    puts JSON.pretty_generate(JSON.parse(object.to_json))
    
    0 讨论(0)
  • 2020-12-12 10:51
    p object
    

    Ruby doc for p.

    p(*args) public

    For each object, directly writes obj.inspect followed by a newline to the program’s standard output.

    0 讨论(0)
  • 2020-12-12 10:52

    The to_yaml method seems to be useful sometimes:

    $foo = {:name => "Clem", :age => 43}
    
    puts $foo.to_yaml
    

    returns

    --- 
    :age: 43
    :name: Clem
    

    (Does this depend on some YAML module being loaded? Or would that typically be available?)

    0 讨论(0)
  • 2020-12-12 10:52

    I came across this thread because I was looking for something similar. I like the responses and they gave me some ideas so I tested the .to_hash method and worked really well for the use case too. soo:

    object.to_hash

    0 讨论(0)
  • 2020-12-12 10:54

    If you're looking for just the instance variables in the object, this might be useful:

    obj.instance_variables.map do |var|
      puts [var, obj.instance_variable_get(var)].join(":")
    end
    

    or as a one-liner for copy and pasting:

    obj.instance_variables.map{|var| puts [var, obj.instance_variable_get(var)].join(":")}
    
    0 讨论(0)
提交回复
热议问题