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?
-
possible duplicate of Returning a part of an array in RubyP Shved– P Shved2010-08-19 19:25:34 +00:00Commented Aug 19, 2010 at 19:25
Add a comment
|
5 Answers
You can use ranges in the array subscript:
arr[100..200]
3 Comments
Dan Heberden
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.
ErikAGriffin
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,3Burak Kaymakci
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.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
1 Comment
Caterpillaraoz
Interesting answer, for second point using two different numbers would fit better: array[100,200] # returns 200 elements from position 100
new_array = old_array.first(200) - old_array.first(100)
3 Comments
deb
That makes sense :). I was wondering if there was a method for this
DarkDust
That one creates two temporary arrays and then does a set difference... not space and time efficient, I think.
Sam 山
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.