简体   繁体   English

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

[英]How to continuosly loop over array values from another loop?

I've got a array of numbers for example : 我有一个数字数组,例如:

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

And number of constants: 和常数的数量:

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

When I iterate over a I want to get a title for each item like this : 当我遍历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'

So when I run over titles start from the begining, this is what I have now : 因此,当我从头开始研究标题时,​​这就是我现在所拥有的:

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

But this doesn't work unfortunately I get a nil title for the last item of a . 但是,这并不遗憾的是工作,我得到一个nil供的最后一项冠军a How can I make this work? 我该如何进行这项工作?

You can use the zip and cycle methods like this: 您可以使用如下所示的zipcycle方法:

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

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

The kind-of-obvious way uses #each_with_index 显而易见的方法使用#each_with_index

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

Or, try something like this... 或者,尝试这样的事情...

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

What about: 关于什么:

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
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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM