0
x = []
a = [1,2,3]
a.each{|i| x<<i; x<<i}

回报:

[1,1,2,2,3,3]

Ruby 是否有内置或更快的方法来执行此操作?

4

4 回答 4

3
a = [1, 2, 3]
n = 2

a.flat_map {|i| [i]*n} # => [1, 1, 2, 2, 3, 3]
于 2012-09-27T12:17:01.787 回答
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]
于 2012-09-27T09:56:11.950 回答
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}}
于 2012-09-27T10:00:12.887 回答
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)
于 2012-09-27T10:05:35.567 回答