How to select array elements in a given range in Ruby?

前端 未结 5 1168
傲寒
傲寒 2021-02-05 03:21

I have an array with let\'s say, 500 elements. I know I can select the first 100 by doing .first(100), my question is how do I select elements from 100 to 200?

5条回答
  •  我在风中等你
    2021-02-05 03:53

    dvcolgan’s answer is right, but it sounds like you might be trying to break your array into groups of 100. If that’s the case, there’s a convenient built-in method for that:

    nums = (1..500).to_a
    
    nums.each_slice(100) do |slice|
      puts slice.size
    end
    
    # => 100, 100, 100, 100, 100
    

提交回复
热议问题