315

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.

Andrew Grimm
  • 78,473
  • 57
  • 200
  • 338
roryf
  • 29,592
  • 16
  • 81
  • 103

11 Answers11

484

Possibly:

puts variable.inspect
Christian Lescuyer
  • 18,893
  • 5
  • 49
  • 45
  • 17
    Adding an [`inspect`](http://www.ruby-doc.org/ruby-1.9/classes/Object.html#M000225) method to your class allows you to define how the class' attributes are displayed, rather than rely on default output. A lot of classes don't implement it well, but it can be really useful when debugging. Ruby will fall back to `to_s` if it can't find an inspect` method. – the Tin Man Nov 27 '10 at 21:45
  • 5
    Current link is broken, See this one http://ruby-doc.org/core-2.0/Object.html#method-i-inspect – SamFlushing Aug 26 '13 at 13:46
  • 7
    `server = TCPServer.new 0 ; puts server.inspect # => nil `. it won't work for most complex objects. – ribamar Jul 25 '16 at 14:13
  • 1
    As this is the first answer found when looking for a php `var_dump` equivalent in ruby, i found that `pp` is much usaful in that case, look here - http://stackoverflow.com/questions/6501506/ruby-inspect-readability/6501569#6501569 – Rabin Sep 07 '16 at 12:45
  • Note that `p object` is an [alias](http://ruby-doc.org/core-2.5.0/Kernel.html#method-i-p) for `puts object.inspect` – Jan Klimo Mar 26 '18 at 05:42
60

You might find a use for the methods method which returns an array of methods for an object. It's not the same as print_r, but still useful at times.

>> "Hello".methods.sort
=> ["%", "*", "+", "<", "<<", "<=", "<=>", "==", "===", "=~", ">", ">=", "[]", "[]=", "__id__", "__send__", "all?", "any?", "between?", "capitalize", "capitalize!", "casecmp", "center", "chomp", "chomp!", "chop", "chop!", "class", "clone", "collect", "concat", "count", "crypt", "delete", "delete!", "detect", "display", "downcase", "downcase!", "dump", "dup", "each", "each_byte", "each_line", "each_with_index", "empty?", "entries", "eql?", "equal?", "extend", "find", "find_all", "freeze", "frozen?", "grep", "gsub", "gsub!", "hash", "hex", "id", "include?", "index", "inject", "insert", "inspect", "instance_eval", "instance_of?", "instance_variable_defined?", "instance_variable_get", "instance_variable_set", "instance_variables", "intern", "is_a?", "is_binary_data?", "is_complex_yaml?", "kind_of?", "length", "ljust", "lstrip", "lstrip!", "map", "match", "max", "member?", "method", "methods", "min", "next", "next!", "nil?", "object_id", "oct", "partition", "private_methods", "protected_methods", "public_methods", "reject", "replace", "respond_to?", "reverse", "reverse!", "rindex", "rjust", "rstrip", "rstrip!", "scan", "select", "send", "singleton_methods", "size", "slice", "slice!", "sort", "sort_by", "split", "squeeze", "squeeze!", "strip", "strip!", "sub", "sub!", "succ", "succ!", "sum", "swapcase", "swapcase!", "taguri", "taguri=", "taint", "tainted?", "to_a", "to_f", "to_i", "to_s", "to_str", "to_sym", "to_yaml", "to_yaml_properties", "to_yaml_style", "tr", "tr!", "tr_s", "tr_s!", "type", "unpack", "untaint", "upcase", "upcase!", "upto", "zip"]
dylanfm
  • 6,292
  • 5
  • 28
  • 29
  • 11
    Using introspection is part of the fun of Ruby. It's often useful to subtract an Object's `instance_methods` from the class' in question to get the methods that are unique: `(String.instance_methods - Object.instance_methods).sort` – the Tin Man Nov 27 '10 at 22:05
  • 3
    this should be the correct answer as I was expecting this when finding this page. – jaycode Sep 13 '11 at 12:37
  • `.methods.sort` is very useful. Is there any 'smart' way to quickly show methods that are (vaguely) unique to that particular object? E.g. a method like `.to_s` might show up often so it's not all that useful, but some it could be very handy to know of certain methods for certain objects. Especially in cases that aren't obvious. Is there any way to quickly get these? (case in point, I have a `PG::Result` object, and want to quickly assess the likely methods I could possibly find useful. – stevec Jun 18 '19 at 02:35
56

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

mjs
  • 63,493
  • 27
  • 91
  • 122
  • 3
    Yes, `to_yaml` requires the YAML model to be loaded. It is part of the Ruby standard library, though. – Chuck Oct 07 '09 at 00:02
  • this was helpful when I was trying to inspect an Amazon S3 object in a Rails app console. – Paul Sep 24 '12 at 06:27
33
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.

Cees Timmerman
  • 17,623
  • 11
  • 91
  • 124
rampion
  • 87,131
  • 49
  • 199
  • 315
  • 1
    Isn't that the same as variable.to_s? I've found that just prints an object reference unless the class explicitly overrides it – roryf Dec 10 '08 at 10:47
18

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

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

or as a one-liner for copy and pasting:

obj.instance_variables.each{ |var| puts [var, obj.instance_variable_get(var).inspect].join(":")}
Christopher Oezbek
  • 23,994
  • 6
  • 61
  • 85
Mike
  • 9,692
  • 6
  • 44
  • 61
10

puts foo.to_json

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

tjerk
  • 101
  • 1
  • 2
5

If you want to print an already indented JSON:

require 'json'
...
puts JSON.pretty_generate(JSON.parse(object.to_json))
ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
5

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

Billal Begueradj
  • 20,717
  • 43
  • 112
  • 130
Gregor
  • 65
  • 1
  • 7
4
object.attribute_names

# => ["id", "name", "email", "created_at", "updated_at", "password_digest", "remember_token", "admin", "marketing_permissions", "terms_and_conditions", "disable", "black_list", "zero_cost", "password_reset_token", "password_reset_sent_at"]


object.attributes.values

# => [1, "tom", "tom@tom.com", Tue, 02 Jun 2015 00:16:03 UTC +00:00, Tue, 02 Jun 2015 00:22:35 UTC +00:00, "$2a$10$gUTr3lpHzXvCDhVvizo8Gu/MxiTrazOWmOQqJXMW8gFLvwDftF9Lm", "2dd1829c9fb3af2a36a970acda0efe5c1d471199", true, nil, nil, nil, nil, nil, nil, nil] 
stevendaniels
  • 2,992
  • 1
  • 27
  • 31
Conor
  • 494
  • 6
  • 15
0

pp File.stat('/tmp')

#<File::Stat
 dev=0x1000004,
 ino=71426291,
 mode=041777 (directory rwxrwxrwt),
 nlink=15,
 uid=0 (root),
 gid=0 (wheel),
 rdev=0x0 (0, 0),
 size=480,
 blksize=4096,
 blocks=0,
 atime=2021-04-20 17:50:33.062419819 +0800 (1618912233),
 mtime=2021-04-21 11:35:32.808546288 +0800 (1618976132),
 ctime=2021-04-21 11:35:32.808546288 +0800 (1618976132)>
QETHAN
  • 1
  • 1
0

I'm using own solution to print and debug variables is https://github.com/igorkasyanchuk/wrapped_print

you can simply call user.wp to see in the logs a value of this variable

instead of:

puts "-"*10
puts user.inspect
puts "-"*10
Igor Kasyanchuk
  • 766
  • 6
  • 12