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?
Asked
Active
Viewed 3.8k times
33
-
possible duplicate of [Returning a part of an array in Ruby](http://stackoverflow.com/questions/695290/returning-a-part-of-an-array-in-ruby) – P Shved Aug 19 '10 at 19:25
5 Answers
54
You can use ranges in the array subscript:
arr[100..200]

davidscolgan
- 7,508
- 9
- 59
- 78
-
4You 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. – Dan Heberden Dec 14 '11 at 22:24
-
4Note 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 – ErikAGriffin Nov 27 '18 at 02:22
-
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`. – Burak Kaymakci Apr 01 '19 at 10:36
21
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

jigfox
- 18,057
- 3
- 60
- 73
-
1Interesting answer, for second point using two different numbers would fit better: array[100,200] # returns 200 elements from position 100 – Caterpillaraoz Oct 04 '19 at 10:19
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

Todd Yandell
- 14,656
- 2
- 50
- 37
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.

DarkDust
- 90,870
- 19
- 190
- 224
-4
new_array = old_array.first(200) - old_array.first(100)

thenengah
- 42,557
- 33
- 113
- 157
-
-
That one creates two temporary arrays and then does a set difference... not space and time efficient, I think. – DarkDust Aug 19 '10 at 19:20
-
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. – thenengah Aug 19 '10 at 19:30