给出2个相同大小的字符串数组,例如:
a = ["what's", " programming", " be"]
b = [" your", " question?", " specific."]
你如何将它们插入一个字符串,即:
"what's your programming question? be specific."
答案 0 :(得分:13)
您可以使用zip
将它们组合在一起,flatten
以展开zip
添加的额外数组,并使用join
来获取简单字符串:
a.zip(b).flatten.join
如果您的数组中没有方便的空格:
a = ["what's", "programming", "be"]
b = ["your", "question?", "specific."]
然后你可以调整join
:
a.zip(b).flatten.join(' ')
如果您不确定空格是否存在,您可以将它们放入join
(只是为了确定),然后squeeze
输出任何重复项:
a.zip(b).flatten.join(' ').squeeze(' ')
答案 1 :(得分:2)
p [a, b].transpose.inject(''){|s, (a, b)| s << a << b}
# => "what's your programming question? be specific."
为回应安德鲁的评论而添加
我不反对穆太短的回答;我觉得这很红宝石。但不知何故,使用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
结果(ubuntu linux 11.04上的ruby 1.9.2)
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)