x = []
a = [1,2,3]
a.each{|i| x<<i; x<<i}
返回:
[1,1,2,2,3,3]
Ruby有内置或更快的方法吗?
答案 0 :(得分:3)
a = [1, 2, 3]
n = 2
a.flat_map {|i| [i]*n} # => [1, 1, 2, 2, 3, 3]
答案 1 :(得分:2)
a = [1,2,3]
a = (a*2).sort
#=> [1,1,2,2,3,3]
a.map{ |i| [i,i] }.flatten
#=> [1,1,2,2,3,3]
答案 2 :(得分:2)
a.zip(a).flatten
或者,如果您需要重复n
次,
a.zip(*[a]*(n-1)).flatten
基于注入(技术上,each_with_object):
a.each_with_object([]){|e, acc| n.times{acc << e}}
答案 3 :(得分:1)
一般来说:
Benchmark.measure{1000000.times{x=[]; a.each{|i| x<<i; x<<i}}}
1.530000 0.000000 1.530000 ( 1.552974)
Benchmark.measure{1000000.times{a.zip(a).flatten}}
4.140000 0.000000 4.140000 ( 4.136788)
Benchmark.measure{1000000.times{a.collect{|i| [i, i]}.flatten}}
4.150000 0.000000 4.150000 ( 4.158172)
在这种特殊情况下,fl00r的答案是最快的:
Benchmark.measure{1000000.times{(a*2).sort}}
1.170000 0.000000 1.170000 ( 1.173677)