From: Brian Adkins Date: 2007-12-12T23:15:06+09:00 Subject: Re: Find the first non-nil element in an array On Dec 11, 5:06 pm, Clifford Heath wrote: > I can't work out why you want to build a new (compacted) array in > order to discard it and use the first element. Detect is much more > suitable: Depending on the nature of the array (in particular, the number of initial nils), speed might be a reason to use compact instead of detect. Although it seems counterintuitive, creating a new compacted array just to grab the first element and throw it away can be faster than using detect. With the compact approach, there is one call to a method that is compiled C code. With the detect approach, there are (possibly) multiple iterations of interpreted Ruby. I'd say compact is perfectly suitable for this purpose - it's more concise, usually faster and logical. require 'benchmark' include Benchmark ITER = 10000 def bench size, num_nils xs = Array.new(size, 'a') xs.fill(nil, 0, num_nils) bm(5) do |bench| bench.report('compact') do ITER.times { xs.compact[0] } end bench.report('detect') do ITER.times { xs.detect {|e| !e.nil? } } end end end [10,100,1000].each do |size| [0,1,9].each do |nils| bench(size, nils) end end -- Brian Adkins http://www.lojic.com http://lojic.com/blog/