How do I dump an object's fields to the consol

2019-01-29 17:49发布

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_r() that will work with arrays as well.

9条回答
\"骚年 ilove
2楼-- · 2019-01-29 18:13
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.

查看更多
Melony?
3楼-- · 2019-01-29 18:18

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(":")}
查看更多
贪生不怕死
4楼-- · 2019-01-29 18:20

If you want to print an already indented JSON:

require 'json'
...
puts JSON.pretty_generate(JSON.parse(object.to_json))
查看更多
一夜七次
5楼-- · 2019-01-29 18:23

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?)

查看更多
走好不送
6楼-- · 2019-01-29 18:23

puts foo.to_json

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

查看更多
爱情/是我丢掉的垃圾
7楼-- · 2019-01-29 18:24

Possibly:

puts variable.inspect
查看更多
登录 后发表回答