Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get nth element of an array in Ruby?

I have a simple array and I am trying to grab every 2nd item in the array. Unfortunately I am more familiar with JavaScript than Ruby...

In JavaScript I could simply do

var arr = [1, 'foo', 'bar', 'baz', 9],
    otherArr = [];

for (i=0; i < arr.length; i=i+2) {
    // Do something... for example:
    otherArr.push( arr[i] );
}

Now how can I do this in Ruby?

like image 276
user3048402 Avatar asked Apr 26 '14 16:04

user3048402


People also ask

How do you return the number of elements in an array in Ruby?

Ruby | Array count() operation Array#count() : count() is a Array class method which returns the number of elements in the array. It can also find the total number of a particular element in the array. Syntax: Array. count() Parameter: obj - specific element to found Return: removes all the nil values from the array.

How do I find the second element of an array?

To get the second to last element in an array, use bracket notation to access the array at index array. length - 2 , e.g. arr[arr. length - 2] . The last element in an array has an index of array.

What does .shift do in Ruby?

The shift() is an inbuilt function in Ruby returns the element in the front of the SizedQueue and removes it from the SizedQueue. Parameters: The function does not takes any element.


2 Answers

For

arr = [1, 'foo', 'bar', 'baz', 9]
new_array = []

To get the odds,

arr.each_with_index{|x, i| new_array << x if i.odd?} 
new_array #=> ['foo', 'baz']

And the evens,

arr.each_with_index{|x, i| new_array.push(x) if i.even?} #more javascript-y with #push
new_array #=> [1, 'bar', 9]
like image 55
stevenspiel Avatar answered Oct 03 '22 16:10

stevenspiel


A nice way is to take each pair, and select only the first in the pair:

arr = [1, 'foo', 'bar', 'baz', 9]
other_arr = arr.each_slice(2).map(&:first)
# => [1, "bar", 9] 
like image 43
Uri Agassi Avatar answered Oct 03 '22 14:10

Uri Agassi