如何从另一个循环连续循环数组值?

时间:2014-03-25 14:37:56

标签: ruby arrays

我有一组数字,例如:

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

但是这不起作用,遗憾的是我为nil的最后一项获得了a标题。我怎样才能做到这一点?

4 个答案:

答案 0 :(得分: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"]
# ...

答案 1 :(得分: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

答案 2 :(得分: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

答案 3 :(得分: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