uses of Ruby’s Object#tap

Ruby 1.9’s Object#tap method has always seemed useful to me, but until now I hadn’t met the chance to use it. Every other time it seemed like abusing it in some way.

Now I came to an old code. Consider this:

I needed to turn that maxlength into a conditional attribute (omiting it if it’s nil).
One way would have been extracting the attributes into a separate variable:

But this separates visually the cgi.text_field() call from it’s arguments, which I don’t like. Tap to the resque:

Now, isn’t that nice! (OK, maybe it isn’t, but at least it is encompassed in the method call and makes it easy to spot all attributes).

Be Sociable, Share!

Leave a Reply