我有以下数组:
arr = ['aaa', 'bbb', 'ccc']
如何在9
次重复打印其值?
我试过以下它并且工作正常,但是任何更好的解决方案都值得赞赏:
total_elements = arr.length
new_index = 0
limit_value = 9
limit_value.times do |index|
if index < total_elements
new_index = index
else
new_index = 0 unless new_index < total_elements
end
puts arr[new_index]
new_index += 1
end
答案 0 :(得分:2)
使用cycle
+ take
arr = ['aaa', 'bbb', 'ccc', 'ddd']
puts arr.cycle.take(9)
# >> aaa
# >> bbb
# >> ccc
# >> ddd
# >> aaa
# >> bbb
# >> ccc
# >> ddd
# >> aaa