2014-03-25 32 views
1

我已經得到了數例如數組:如何連續循環來自另一個循環的數組值?

a = [1,2,3,4,5,6,7,8,9,10,11] 

而且一些常量:

TITLES = ['a', 'b', 'c', 'd'] 

當我遍歷a我希望得到一個標題這樣每個項目:

- iterating over a, first item (1) get title 'a' 
- iterating over a, first item (2) get title 'b' 
- iterating over a, first item (3) get title 'c' 
- iterating over a, first item (4) get title 'd' 
- iterating over a, first item (5) get title 'a' 
- iterating over a, first item (6) get title 'b' 

所以,當我跑過來的標題從一開始啓動,這是我現在有:

a.each_with_index do |m, i| 
    if TITLES[i].nil? 
    title = TITLES[(i - TITLES.length)] 
    else 
    title = TITLES[i] 
    end 
end 

但是,這不起作用,不幸的是我得到a的最後一項nil標題。我該如何做這項工作?

+0

你總是有4個常量嗎?如果是這樣,你可以切成4塊,然後遍歷它們 –

+2

嘗試'title = TITLES [i%TITLES.length]' – iamnotmaynard

回答

1

一種顯而易見的 - 方式使用#each_with_index

a.each_with_index do |x, i| 
    p [x, TITLES[i % TITLES.length]] 
end 

或者,嘗試這樣的事情......

a.zip(TITLES*3).each do |x, y| 
    p [x, y] 
end 
+0

+1第一部分... –

0

什麼:

a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] 
TITLES = ['a', 'b', 'c', 'd'] 

t_length = TITLES.length 

a.each_with_index do |item, index| 
    t_index = index % t_length 
    title = TITLES[t_index] 
    puts "item: #{item} - title: #{title}" 
end 
0
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] 
TITLES = ['a', 'b', 'c', 'd'] 

TITLES = TITLES + TITLES + TITLES 

(a.zip TITLES).each do |p, q| 
    puts "======#{p}==#{q}======" 
end 
3

你可以使用zipcycle方法是這樣的:

a.zip(TITLES.cycle).each do |x, title| 
    p [x, title] 
end 

# Output: 
# [1, "a"] 
# [2, "b"] 
# [3, "c"] 
# [4, "d"] 
# [5, "a"] 
# ...