Ed de Almeida Ed de Almeida - 2 months ago 18
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|
f.write(source.to_s.force_encoding('UTF-8'))
end


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
#tap
method there.

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

Where is this method defined?

What is it for?

Thanks in advance!

Answer

#tap is defined on Object

https://ruby-doc.org/core-2.3.1/Object.html#method-i-tap

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 = []
  a.push(3)
  a
end

def foo
  [].tap do |a|
    a.push(3)
  end
end

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.