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?
views:
70answers:
5That makes sense :). I was wondering if there was a method for this
deb
2010-08-19 19:19:59
That one creates two temporary arrays and then does a set difference... not space and time efficient, I think.
DarkDust
2010-08-19 19:20:46
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.
Sam
2010-08-19 19:30:37
@Sam: If you don't have ruby at your hand, take al look at this: http://TryRuby.org/
jigfox
2010-08-20 08:09:25
Oh, Thanks! Awesome.
Sam
2010-08-20 16:30:02
+1
A:
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
2010-08-19 19:19:21
+3
A:
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
2010-08-19 19:19:45
+1
A:
dvcolgan’s answer is quite 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
2010-08-19 20:46:01