循环遍历数组 [英] Looping through an array with 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中做同样的事,但找不到办法步。一个而
循环可以完成这项工作,但我觉得使用它已经很大了,并且期望有更好的(更多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.
推荐答案
范围有步骤
方法,您可以使用该方法跳过索引:
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
这篇关于循环遍历数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文