Most exceptions are caused by unexpected data being passed to methods that work fine otherwise, so it's often useful to trace a piece of data through your application to find the cause of an error. In this article, we'll go over inspecting data in Ruby and Rails applications.
puts
, #inspect
and p
Ruby's puts
method is used to print a message to the console.
When running the script above, the value is printed out to allow you to see what's inside.
$ ruby puts.rb This is a string
However, if the unknown
variable holds an empty string, a nil
value or an empty hash, puts
will print an empty line. With that, you won't be able to see its exact value, and you won't be able to differentiate between empty hashes and strings, for example.
$ ruby puts_empty_string.rb
Luckily, there's an instance method named inspect, which is implemented on every object you'll encounter. It will return a string representation of the object.
For an empty string, it'll return a pair of quotes, and for an array, it'll return a pair of brackets.
$ ruby inspect_empty_string.rb "" $ ruby inspect_empty_array.rb []
Since the combination of puts
and inspect
are used so often, there's a shortcut that does both in one go, called p
. It does the exact same thing, but it's quicker to type.
Inspecting data in Rails views
Although there's the p
shortcut, it's still useful to know about the inspect
method when you need a string representation of an object without printing it to the console.
In a Rails view, for example, it's sometimes more useful to print the value to the resulting HTML page instead of having to find it in the log.
When inspecting more complex data structures, it's sometimes difficult to find the data you're looking for, because the inspected value is printed on a single line.
Rails provides the debug
helper to get around this. Instead of just inspecting the value, it will convert the object to a human readable YAML representation and put it in <pre>
tags to preserve formatting.
The debug
helper uses the to_yaml
method under the hood to get the YAML representation, before wrapping it in a <pre>
block. To convert an object to a YAML representation without wrapping it in a <pre>
tag, you can use #to_yaml
on any object directly.
As you've come to expect, there's a shortcut for printing a YAML representation of an object too. The example above can be called in one go by using y Product.first
.
"puts"-debugging
There are more ways to inspect data in your applications, like the Pry library and Ruby's own debugger. While it's certainly a good idea to check out other methods of inspecting data, writing a log to the console or showing a piece of data in a view is often the quickest way to find out what's happening.
We’d love to know how you liked this article, if you have any questions about it, and what you’d like to read about next, so be sure to let us know at @AppSignal.