Eavesdropping on Expressions - Moonbase
- class Object
def tap
yield self
self
end
end - xs = blah.sort.grep( /foo/ )
p xs
# do whatever we had been doing with the original expression
xs.map { |x| x.blah } With
Object#tap, this becomes much easier—you can just slip it in without radically modifying the code:blah.sort.grep( /foo/ ).tap { |xs| p xs }.map { |x| x.blah }The traditional way:
def blah
sum = @things.map { |x|
x.length
}.inject( 0 ) { |a, b|
a + b
}
p sum
sum
endThe
Object#tapway:def blah
@things.map { |x|
x.length
}.inject( 0 ) { |a, b|
a + b
}.tap { |sum| p sum }
end
Posted from Diigo. The rest of my favorite links are here.
没有评论:
发表评论