Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

arrays

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?

like image 832
deb Avatar asked Aug 19 '10 19:08

deb


People also ask

How do you access the elements of an array in Ruby?

The find method locates and returns the first element in the array that matches a condition you specify. find executes the block you provide for each element in the array. If the last expression in the block evaluates to true , the find method returns the value and stops iterating.

How do you select an array in Ruby?

Ruby | Array select() function Array#select() : select() is a Array class method which returns a new array containing all elements of array for which the given block returns a true value. Return: A new array containing all elements of array for which the given block returns a true value.

How do you find the subset of an array in Ruby?

slice() is a method in Ruby that is used to return a sub-array of an array. It does this either by giving the index of the element or by providing the index position and the range of elements to return.


1 Answers

You can use ranges in the array subscript:

arr[100..200] 
like image 65
davidscolgan Avatar answered Oct 09 '22 19:10

davidscolgan