deb
deb

Reputation: 12814

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

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?

Upvotes: 35

Views: 40128

Answers (5)

Todd Yandell
Todd Yandell

Reputation: 14696

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

Upvotes: 14

dvcolgan
dvcolgan

Reputation: 7728

You can use ranges in the array subscript:

arr[100..200]

Upvotes: 56

jigfox
jigfox

Reputation: 18185

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

Upvotes: 22

DarkDust
DarkDust

Reputation: 92336

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.

Upvotes: 3

Sam 山
Sam 山

Reputation: 42865

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

Upvotes: -4

Related Questions