http://www.ruby-doc.org/core-1.9/classes/Object.html#M000191
Yields x to the block, and then returns x. The primary purpose of this method is to "tap into" a method chain, in order to perform operations on intermediate results within the chain.
(1..10) .tap {|x| puts "original: #{x.inspect}"}
.to_a .tap {|x| puts "array: #{x.inspect}"}
.select {|x| x%2==0} .tap {|x| puts "evens: #{x.inspect}"}
.map { |x| x*x } .tap {|x| puts "squares: #{x.inspect}"}
For the second example, I think I'd even prefer:
Essentially the same as
ugly
, but suggests the Extract Method I'd do if there were other behaviors in the original method.I don't think the responsibility for doing that yield/return dance really lies with any given Object. So far, I think I'd almost always rather extract a method, unless it's doing something like MenTaLguY's original implementation (first example), just for debugging purposes. Leaving it there for production code is a bit of a harder sell for me.