From: David Masover Date: 2010-07-29T11:40:11+09:00 Subject: Re: Object#tap (was Nice algorithm for 'spreading' indexes across an array?) On Wednesday, July 28, 2010 09:03:18 am Harry Kakueki wrote: > Is there any problem using Object#tap in this way? > I saw some examples, but in the examples the object was not modified > in the block. Oh, you mean modifying the array? > class Array > def spread(n) > dup.tap{|a| (size-n).downto(1).map{|b| size*b/(size-n+1)}.each{|c| > a.delete_at(c)}} > end > end Not particularly. The thing you have to be careful of is reassigning it -- for example, this wouldn't work: 1.tap {|x| x+=1} You have to actually modify the object. For example, if we're talking about arrays, instead of this: string.tap {|x| x + 'foo'} Do this: string.tap {|x| x << 'foo'} It seems like << returns self, so that's completely unnecessary, you could just do this: (string << 'foo') ...but hopefully it illustrates the point. I have a feeling I'm overcomplicating things, though. Here's one possible implementation of Object#tap: class Object def tap yield self self end end Nothing mysterious about it at all. (MRI might do it in C, I'm not sure, but the above works.)