Looping through an array with step

后端 未结 7 1077
余生分开走
余生分开走 2020-12-05 23:24

I want to look at every n-th elements in an array. In C++, I\'d do this:

for(int x = 0; x

        
7条回答
  •  鱼传尺愫
    2020-12-06 00:21

    Ranges have a step method which you can use to skip through the indexes:

    (0..array.length - 1).step(2).each do |index|
      value_you_care_about = array[index]
    end
    

    Or if you are comfortable using ... with ranges the following is a bit more concise:

    (0...array.length).step(2).each do |index|
      value_you_care_about = array[index]
    end
    

提交回复
热议问题