Carlo Pecchia

Ruby 1.9: chain methods powered

(15.04.2010)

Often we use the “chain methods” technique to perform some operations on the same object in a “concise” way:

puts "apples".reverse.upcase
# => SELPPA

How handy could be to do something “outside” the chain without leaving it?

The new method tap was introduced (and backported to 1.8 too):

puts "apples".reverse
             .tap{ |o| puts "reversed: #{o}" }
             .upcase

# => reversed: selppa
# => SELPPA

As we can see it is really easy to code:

class Object
  def tap
    yield self
    self
  end
end
Italiano

Sei interessato a conoscere tutte le principali novità di Ruby 1.9?

Vedi lo screeencast "pillola" su ThinkCode.TV

Picture credits to Ashu Mittal