How to wrap 2 string arrays in one string in Ruby?

Given 2 string arrays of the same size, for example:

a = ["what's", " programming", " be"]
b = [" your", " question?", " specific."]

How would you alternate them in one line, that is:

"what your programming question? be specific."

?

+3
source share
2 answers

You can use zipto combine them, flattento smooth out additional arrays added zip, and jointo get a simple string:

a.zip(b).flatten.join

And if you didn’t have convenient spaces in your arrays:

a = ["what's", "programming", "be"]
b = ["your", "question?", "specific."]

Then you can configure join:

a.zip(b).flatten.join(' ')

And if you were not sure that there were spaces or not, you can put them in join(just to make sure), and then squeezefrom any duplicates:

a.zip(b).flatten.join(' ').squeeze(' ')
+13
source
p [a, b].transpose.inject(''){|s, (a, b)| s << a << b}
# => "what your programming question? be specific."

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)
+2

All Articles