Saturday, June 26, 2010

Using Object#tap

Object#tap is new to Ruby 1.9. This new method will allow us to modify the object its called upon and, after the block finishes, will return to us the original object.

We can use this feature to make our specs a bit more concise.

Here is an example using this spec...


describe Array do
   before(:all) do
    @array = Array.new
    @array << 1
   end
   
   it "should have a length of 1" do
    @array.should have(1).element
   end   
end

We change it so.

describe Array do
   before(:all) {@array = Array.new.tap{|me| me << 1}}
   
   it "should have a length of 1" do
    @array.should have(1).element
   end   
end

This code says "create a new instance of class Array, pass it to the 'tap' block, modify it, and return the original now modified object."

@array = Array.new.tap{|me| me << 1}

No comments: