2016-10-30 1 views
0

전체 배열을 반복하고 싶습니다. 어느 위치에서 시작 하든지합니다. Ruby에서이를 쉽게 수행 할 수있는 방법이 있는지 확실하지 않으며 Array 또는 Enumerator 문서에서 예제를 찾을 수 없습니다.루비 : n 번째 위치에서 전체 배열을 반복합니다.

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

이의 rotate 방법을 사용할 수 있습니다. 이 메서드는 각 요소의 위치를 ​​n만큼 회전합니다. 그래서 예를 들면이

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

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

주와 같이 수행 할 수 있습니다 : 두 번째 방법에 대한 n의 부정적인 색인을 찾아 유도 할 수있다 회전 매개 변수를. 그래서 이것을 위해 인덱스 3의 요소는 길이 5의 인덱스 -2에 있습니다.

+1

완벽! 학습 경험에 감사드립니다! – user3281384

+0

@ user3281384 걱정할 필요가 없습니다. 좋은 질문! –

+0

'회전'좋은 지점. 각각의 {| e | e}는 두 예제의 요구 사항에 불필요한 것처럼 보입니다. –

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 '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 
: 배열 인덱스에 의해 메모리 벤치 마크, 반복, 특히 큰 배열 크기에, 적은 메모리 배고픈로

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) 

하지만,