p [a, b].transpose.inject(''){|s, (a, b)| s << a << b}
Posted in response to comment by Andrew
- ; , . - inject each_with_object , flatten join. .
a = ["what's", " programming", "be"]
b = [" your", " question?", " specific."]
$n = 1000000
Benchmark.bmbm do |br|
br.report('flatten join'){$n.times{
a.zip(b).flatten.join
}}
br.report('inject'){$n.times{
[a, b].transpose.inject(''){|s, (a, b)| s << a << b}
}}
br.report('each_with_object'){$n.times{
[a, b].transpose.each_with_object(''){|(a, b), s| s << a << b}
}}
end
(ruby 1.9.2 ubuntu linux 11.04)
Rehearsal ----------------------------------------------------
flatten join 2.770000 0.000000 2.770000 ( 2.760427)
inject 2.190000 0.000000 2.190000 ( 2.195147)
each_with_object 2.160000 0.000000 2.160000 ( 2.158263)
------------------------------------------- total: 7.120000sec
user system total real
flatten join 2.810000 0.010000 2.820000 ( 2.838118)
inject 2.190000 0.000000 2.190000 ( 2.197567)
each_with_object 2.150000 0.000000 2.150000 ( 2.148922)