我已經得到了數例如數組:如何連續循環來自另一個循環的數組值?
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
標題。我該如何做這項工作?
你總是有4個常量嗎?如果是這樣,你可以切成4塊,然後遍歷它們 –
嘗試'title = TITLES [i%TITLES.length]' – iamnotmaynard