Ruby:从第n个位置迭代整个数组

时间:2016-10-30 00:09:44

标签: ruby

我想从任何位置开始迭代整个数组。我不确定是否有办法在Ruby中轻松实现这一点,我在ArrayEnumerator文档中找不到任何示例。

array = [0, 1, 2, 3, 4]
array.each.starting_at(3) { |e| e }
#=> [3, 4, 0, 1, 2]

还有:

array.each.starting_at_reverse(3) { |e| e }
#=> [3, 2, 1, 0, 4]

2 个答案:

答案 0 :(得分:2)

您可以使用rotate方法。此方法将每个元素的位置旋转n。所以你的例子可以像这样完成

array.rotate(3).each {|e| e }

array.reverse.rotate(1).each {|e| e}

注意:对于第二种方法,可以通过查找n的负索引来导出要旋转的参数。因此,对于此,索引3处的元素位于长度为-2的数组中的索引5

答案 1 :(得分:0)

您可以使用uptodownto Fixnum方法执行此操作:

array = [0, 1, 2, 3, 4]
last_index = array.size - 1

3.upto last_index do |i|
  puts array[i]
end
# => 3, 4

last_index.downto 3 do |i|
  puts array[i]
end
# => 4, 3

PS。作为速度基准,旋转更快的迭代

array.rotate(3).each {|e| puts e}

基准:

require 'benchmark'

array = Array.new(10000000) { rand(1...9) }
last_index = array.size - 1

Benchmark.bm do |x|
  x.report 'upto' do
    10000.upto last_index do |index| a = array[index] + 1; end
  end

  x.report 'downto' do
    last_index.downto 10000 do |index| a = array[index] + 1; end
  end

  x.report 'rotate' do
    array.rotate(10000).each {|e| a = e + 1 }
  end
end

# RESULTS:
# user     system      total        real
# upto    0.680000   0.000000   0.680000 (  0.681932)
# downto  0.680000   0.000000   0.680000 (  0.679752)
# rotate  0.590000   0.040000   0.630000 (  0.622901)

但是,作为内存基准测试,通过数组索引进行迭代可减少内存耗尽,特别是在大数组大小上:

require 'memory_profiler'

array = Array.new(10000000) { rand(1...9) }
last_index = array.size - 1

{
  upto: -> { 10000.upto last_index do |index| a = array[index] + 1; end },
  downto: -> { last_index.downto 10000 do |index| a = array[index] + 1; end },
  rotate: -> { array.rotate(10000).each {|e| a = e + 1 } },
  reverse_rotate: -> { array.reverse.rotate(10000).each {|e| a = e + 1 } }
}.each { |desc, code| puts "#{desc.to_s} => #{MemoryProfiler.report(&code).total_allocated_memsize.to_s}" }

# RESULTS (in bytes):
# upto           => 0          # no additional memory allocation
# downto         => 0          # no additional memory allocation
# rotate         => 80000040   # implicitly copied array 1 time
# reverse_rotate => 160000080  # implicitly copied array 2 times