使用 step 循环遍历数组 [英] Looping through an array with step

查看:18
本文介绍了使用 step 循环遍历数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想查看数组中的每个第 n 个元素.在 C++ 中,我会这样做:

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

for(int x = 0; x<cx; x+=n){
    value_i_care_about = array[x];
    //do something with the value I care about.  
}

我想在 Ruby 中做同样的事情,但找不到步进"的方法.while 循环可以完成这项工作,但我发现在已知大小的情况下使用它会令人反感,并希望有更好(更多 Ruby)的方式来执行此操作.

I want to do the same in Ruby, but can't find a way to "step". A while loop could do the job, but I find it distasteful using it for a known size, and expect there to be a better (more Ruby) way of doing this.

推荐答案

范围有一个 step 方法,您可以使用它来跳过索引:

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

这篇关于使用 step 循环遍历数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆