Looping through an array with step

2020-02-09 06:21发布

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.  
}

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.

7条回答
Animai°情兽
2楼-- · 2020-02-09 06:48

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.

查看更多
Root(大扎)
3楼-- · 2020-02-09 06:50

Just use step() method from Range class which returns an enumerator

(1..10).step(2) {|x| puts x}
查看更多
对你真心纯属浪费
4楼-- · 2020-02-09 06:52

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
查看更多
干净又极端
5楼-- · 2020-02-09 06:53
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

查看更多
何必那么认真
6楼-- · 2020-02-09 06:54

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/

So something like:

array.step(n) do |element|
  # process element
end
查看更多
Ridiculous、
7楼-- · 2020-02-09 06:59
array.each_slice(n) do |e, *_|
  value_i_care_about = e
end
查看更多
登录 后发表回答