Ed de Almeida Ed de Almeida - 1 year ago 100
Ruby Question

Ruby Tempfile#tap: What class defines this method and what is it for?

I've found this piece of code in a pull request someone made to one of my gems:

source = HTTParty.get(PoliticosBR::DEPUTADOS_URL)
tempfile = Tempfile.new('deputados.xls').tap do |f|

The idea is getting a remote Excel file with HTTParty and then write it to a Tempfile for reading its data. Nothing fancy and it is working fine.

But I'm not very used to Ruby Tempfile and then I decided to read its documentation in order to learn more about it. But I haven't found a
method there.

Then I tried the File documentation and then again I could find nothing about

Where is this method defined?

What is it for?

Thanks in advance!

Answer Source

#tap is defined on Object


It was introduced in Ruby 1.9. It yields self to the block and then returns self. I think an illustrative example is when it's used to return an object from a method.

You could do this.

def foo
  a = []

def foo
  [].tap do |a|

In the first example the array a is returned explicitly and in the second tap is being used to yield the block to self and then return self.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download