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
puts foo.to_json
might come in handy since the json module is loaded by default
If you want to print an already indented JSON:
require 'json'
...
puts JSON.pretty_generate(JSON.parse(object.to_json))
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.
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?)
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
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(":")}