给定两个相同大小的字符串数组,例如:
a = ["what's", " programming", " be"]
b = [" your", " question?", " specific."]
你如何将它们交错成一个字符串,即:
"what's your programming question? be specific."
?
p [a, b].transpose.inject(''){|s, (a, b)| s << a << b}
# => "what's your programming question? be specific."
回应安德鲁评论的补充
我对mu is too short的答案没有任何异议;我认为它很符合Ruby的风格。但是,使用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)
flatten
和join
稍微快一些。 - sawaeach_with_object
了吗? - Andrew Grimmeach_with_object
仍然比flatten
和join
快,但略慢于inject
。我认为我测试得没错。你也可以试试吗? - sawaeach_with_object
比inject
更慢可能是值得的。 - Andrew Grimmeach_with_object
和inject
之间的区别微妙,甚至在我另一次基准测试中反过来了。 - sawa