35

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?

1

5 Answers 5

56

You can use ranges in the array subscript:

arr[100..200]
Sign up to request clarification or add additional context in comments.

3 Comments

You can also do negative ranges as well: arr[100..-50] would get the 100th element through the 450th element, in the case of a 500 element array.
Note that in ruby a range with two dots .. represents a range inclusive of the last number, and three dots ... is exclusive. So (1..4) is 1,2,3,4 while (1...4) is 1,2,3
What about arr[1..]? This also worked for me to select from the index 1 to the last index but I do not know whether that is correct or not. Because then RuboCop warns me on RubyMine.
22

You can do it like this:

array[100..200] # returns the elements in range 100..200
# or
array[100,100] # returns 100 elements from position 100

More Information

1 Comment

Interesting answer, for second point using two different numbers would fit better: array[100,200] # returns 200 elements from position 100
14

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

Comments

3
sample_array = (1..500).to_a
elements_100_to_200 = sample_array[100..200]

You can pass a range as index to an array and get a subarray with the queried elements from that subrange.

Comments

-4
new_array = old_array.first(200) - old_array.first(100)

3 Comments

That makes sense :). I was wondering if there was a method for this
That one creates two temporary arrays and then does a set difference... not space and time efficient, I think.
your right. I'm on a win box and don't have ruby on it so I couldn't try other solutions in irb. I also thought about array.find(100..200) but I don't know if it accepts ranges. Try it out.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.