x = []
a = [1,2,3]
a.each{|i| x<<i; x<<i}
回报:
[1,1,2,2,3,3]
Ruby 是否有内置或更快的方法来执行此操作?
a = [1, 2, 3]
n = 2
a.flat_map {|i| [i]*n} # => [1, 1, 2, 2, 3, 3]
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]
a.zip(a).flatten
或者,如果您需要重复n
次数,
a.zip(*[a]*(n-1)).flatten
基于注入的(技术上,each_with_object):
a.each_with_object([]){|e, acc| n.times{acc << e}}
一般来说:
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)