Given 2 string arrays of the same size, e.g.:
a = ["what's", " programming", " be"]
b = [" your", " question?", " specific."]
How would you interleave them into one string, i.e.:
"what's your programming question? be specific."
?
You could use zip to bring them together, flatten to flatten out the extra arrays that zip adds, and join to get a simple string:
a.zip(b).flatten.join
And if you didn't have the convenient spaces in your arrays:
a = ["what's", "programming", "be"]
b = ["your", "question?", "specific."]
Then you could tweak the join:
a.zip(b).flatten.join(' ')
And if you weren't sure if the spaces were there or not, you could put them in with join (just to be sure) and then squeeze out any duplicates:
a.zip(b).flatten.join(' ').squeeze(' ')
p [a, b].transpose.inject(''){|s, (a, b)| s << a << b}
# => "what's your programming question? be specific."
Added in response to Andrew's comment
I have no objection against mu is too short's answer; I think it is pretty rubyish. But somehow, using inject or each_with_object is faster than going with flatten and join. Below is my benchmark.
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
Result (ruby 1.9.2 on 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)
flatten and join.each_with_object?each_with_object is still faster than flatten and join but slightly slower than inject. I think I am testing right. Can you also try?each_with_object is slower than inject.