Last Updated: February 25, 2016
·
326
· tylerhunt

Output Intermediate Values in Ruby

Sometimes with a long chain of method calls like this:

user.photos.collect(&:title).sort.uniq

It may be helpful when debugging code to output one of the intermediate values. This can be done using #tap:

user.photos.tap { |photos| puts photos.inspect }.collect(&:title).sort.uniq

#tap will yield and return the sender, allowing you to inspect a value within the chain without interrupting it.

To make this more convenient in the console, add the following to the file ~/.irbrc:

class Object
  def o
    require 'pp' unless defined?(pp)
    pp self
    self
  end
end

This will allow you to easily inspect elements by inserting .o anywhere in the chain:

user.photos.o.collect(&:title).sort.uniq