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,
Similarly if you try to use to_s method on Model/ActiveRecord object in Rails, it will give something like,
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,
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,
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,
This just has converted object’s reference using to_s
Now tryng with p
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.
Subscribe to Ruby in Rails
Get the latest posts delivered right to your inbox