Looping through an array with step

后端 未结 7 1043
余生分开走
余生分开走 2020-12-05 23:24

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

for(int x = 0; x

        
相关标签:
7条回答
  • 2020-12-05 23:58
    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

    0 讨论(0)
  • 2020-12-06 00:00
    array.each_slice(n) do |e, *_|
      value_i_care_about = e
    end
    
    0 讨论(0)
  • 2020-12-06 00:02

    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
    
    0 讨论(0)
  • 2020-12-06 00:09

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

    (1..10).step(2) {|x| puts x}
    
    0 讨论(0)
  • 2020-12-06 00:19

    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"
    
    0 讨论(0)
  • 2020-12-06 00:21

    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
    
    0 讨论(0)
提交回复
热议问题