From: James Edward Gray II Date: 2007-11-17T02:20:24+09:00 Subject: Re: wondering about #tap (was: Re: Thoughts about Array#compact!, Array#flatten!, Array#reject!, String#strip!, String#capitalize!, String#gsub!, etc.) On Nov 16, 2007, at 10:36 AM, Nikolai Weibull wrote: > On Nov 16, 2007 12:40 PM, David A. Black wrote: > >> It's interesting that almost every example of #tap ends up saying >> that >> it's probably better not to use it, for one reason or another >> (usually >> readability; sometimes the dangers of mixing bang and non-bang >> methods). >> >> It makes me wonder whether the main effect of #tap is going to be a >> lot of warnings that it isn't a best practice. Or are there examples >> that *don't* look worse than the alternatives? > > def cleverly_return_an_array_after_building_it > Array.new.tap do |ary| > [1, 2, 3].each do |i| > ary << i > end > end > end > > instead of > > def return_an_array_in_an_unclever_fashion_after_building_it > ary = [] > [1, 2, 3].each do |i| > ary << i > end > ary > end Why not: def build_array Array.new(3) do { |i| i } # if (1..3).to_a is cheating end James Edward Gray II