循环遍历数组

baa*_*h05 22 ruby iteration loops

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

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

我想在Ruby中做同样的事情,但找不到"步"的方法.一个while循环可以做的工作,但我觉得它难吃使用它的已知大小,并期待有一个更好的(更红宝石)这样做的方式.

小智 42

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

(0..array.length - 1).step(2).each do |index|
  value_you_care_about = array[index]
end
Run Code Online (Sandbox Code Playgroud)

或者,如果您习惯使用...范围,则以下内容更为简洁:

(0...array.length).step(2).each do |index|
  value_you_care_about = array[index]
end
Run Code Online (Sandbox Code Playgroud)

  • 您可以使用`(0 ... array.length)`而不是`(0..array.length - 1)` (5认同)

saw*_*awa 18

array.each_slice(n) do |e, *_|
  value_i_care_about = e
end
Run Code Online (Sandbox Code Playgroud)


boc*_*lus 5

只需使用Range类中的step()方法,它返回一个枚举器

(1..10).step(2) {|x| puts x}
Run Code Online (Sandbox Code Playgroud)