If your array is a simple array in which there are no other arrays, then I would use the hash matrix dereferencing method:
Hash[*[1,2,3,4].zip(Array.new(4,0)).flatten]
Or perhaps a more general one:
If there are nested arrays, you only need to smooth out one level of depth, and since there is no ruby โโcommand for flatten_once, you just need to do it manually using concatenation. Surface - you can alternate zeros during concatenation, so you no longer need to fasten it:
Hash[*[1,2,3,4].inject([]){|s,x| s.concat([x,0])}]
A quick scan of 1,000,000 iterations of each on my machine in Ruby 1.8.6 gives me:
aforementioned merge! method: 34s Hash[*...).concat([x,0])}] method: 25s aforementioned result! method: 22s Hash[*...).flatten] method: 15s
source share