ruby 循环遍历数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13021812/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Looping through an array with step
提问by baash05
I want to look at every n-th elements in an array. In C++, I'd do this:
我想查看数组中的每个第 n 个元素。在 C++ 中,我会这样做:
for(int x = 0; x<cx; x+=n){
value_i_care_about = array[x];
//do something with the value I care about.
}
I want to do the same in Ruby, but can't find a way to "step". A whileloop 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.
我想在 Ruby 中做同样的事情,但找不到“步进”的方法。一个while循环可以做的工作,但我觉得它难吃使用它的已知大小,并期待有一个更好的(更红宝石)这样做的方式。
回答by
Ranges have a stepmethod which you can use to skip through the indexes:
范围有一种step方法可用于跳过索引:
(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
回答by sawa
array.each_slice(n) do |e, *_|
value_i_care_about = e
end
回答by boctulus
Just use step() method from Range class which returns an enumerator
只需使用 Range 类中的 step() 方法,该方法返回一个枚举器
(1..10).step(2) {|x| puts x}
回答by bdeonovic
We can iterate while skipping over a range of numbers on every iteration e.g.:
我们可以在每次迭代时跳过一系列数字进行迭代,例如:
1.step(10, 2) { |i| print "#{i} "}
http://www.skorks.com/2009/09/a-wealth-of-ruby-loops-and-iterators/
http://www.skorks.com/2009/09/a-wealth-of-ruby-loops-and-iterators/
So something like:
所以像:
array.step(n) do |element|
# process element
end
回答by doesterr
This is a great example for the use of the modulo operator %
这是使用模运算符的一个很好的例子 %
When you grasp this concept, you can apply it in a great number of different programming languages, without having to know them in and out.
当您掌握了这个概念时,您就可以将其应用到大量不同的编程语言中,而无需深入了解它们。
step = 2
["1st","2nd","3rd","4th","5th","6th"].each_with_index do |element, index|
puts element if index % step == 1
end
#=> "2nd"
#=> "4th"
#=> "6th"
回答by Jurriaan
What about:
关于什么:
> [1, 2, 3, 4, 5, 6, 7].select.each_with_index { |_,i| i % 2 == 0 }
=> [1, 3, 5, 7]
Chaining of iterators is very useful.
迭代器的链接非常有用。
回答by syllabix
class Array
def step(interval, &block)
((interval -1)...self.length).step(interval) do |value|
block.call(self[value])
end
end
end
You could add the method to the class Array
您可以将该方法添加到类 Array

