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?
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.
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.
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.
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]
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With