Difference between to_s and inspect in Ruby

While running a script in Ruby, we usually want to log data from objects for debugging purpose  puts, p, logger methods are used to log along with to_s, inspect methods to log object. This tutorial will give brief about each method and when to use which one.

1. to_s

to_s is very common method used by Ruby programmers to get String representation of object on which it is called. For example,

considering fixnum,

12345.to_s => '12345'

Similarly if you try to use to_s method on Model/ActiveRecord object in Rails, it will give something like,

User.first.to_s
#<User:0x007fd15cc57238>

Which is object’s representation in string. User: Class name, 0x007fd15cc57238: based on object id.

Using String Interpolation:

Whenever you use String Interpolation, Ruby calls by default to_s method on objects used in the String interpolation before printing output.

For example,

user = User.first
puts "This is #{user} information"
"This is #<User:0x007fefb2002428> information"

This show that while processing string interpolation user object is converted to to_s internally.

2. inspect

inspect method is more of a developer-friendly version of to_s. For Model/ActiveRecord you can check out definition of inspect on APIDock

Considering same example as above,

user = User.first
puts "This is #{user.inspect} information"
This is #<User id: 1, email: "[email protected]", encrypted_password: "$2a$10$D57y73Q9HUXG9Hym3bLl8.MizOdTRxd6NQH6snHi4Q....", reset_password_token: nil, reset_password_sent_at: nil, remember_created_at: "2014-10-15 11:19:09", sign_in_count: 13, current_sign_in_at: "2014-10-21 20:10:18", last_sign_in_at: "2014-10-20 17:37:27", current_sign_in_ip: "127.0.0.1", last_sign_in_ip: "127.0.0.1", created_at: "2014-06-30 17:41:06", updated_at: "2014-10-21 20:10:18"> information"

This clearly depicts how much useful inspect is instead of to_s on objects for logging and debugging purposes.

3. p vs puts

When you use puts for printing, then puts internally uses to_s on objects before processing inputs, while p uses inspect on objects before processing inputs.

E.g. Again considering same example,

user = User.first
puts user
#<User:0x007fefb0c690b0>

This just has converted object’s reference using to_s

Now tryng with p

p user
#<User id: 1, email: "[email protected]", encrypted_password: "$2a$10$D57y73Q9HUXG9Hym3bLl8.MizOdTRxd6NQH6snHi4Q....", reset_password_token: nil, reset_password_sent_at: nil, remember_created_at: "2014-10-15 11:19:09", sign_in_count: 13, current_sign_in_at: "2014-10-21 20:10:18", last_sign_in_at: "2014-10-20 17:37:27", current_sign_in_ip: "127.0.0.1", last_sign_in_ip: "127.0.0.1", created_at: "2014-06-30 17:41:06", updated_at: "2014-10-21 20:10:18">

Thus, you may prefer using p instead of to_s if you are looking purely for logging/ debugging purposes. Otherwise use of these methods purely depends on the required functionality though.