Get the nth element of an array in Ruby?

I have a simple array, and I'm trying to capture every second element of the array. Unfortunately, I'm more familiar with JavaScript than with Ruby ...

In JavaScript, I could just 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?

+4
source share
7 answers
n = 2
a = ["a", "b", "c", "d"]
b = (n - 1).step(a.size - 1, n).map{ |i| a[i] }

output => ["b", "d"] 

Try to execute code

+2
source

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 evens,

arr.each_with_index{|x, i| new_array.push(x) if i.even?} #more javascript-y with #push
new_array #=> [1, 'bar', 9]
+3
source

- :

arr = [1, 'foo', 'bar', 'baz', 9]
other_arr = arr.each_slice(2).map(&:first)
# => [1, "bar", 9] 
+3

Array#select Enumerator#with_index:

arr.select.with_index { |e, i| i.even? }
#=> [1, "bar", 9]

, 1- :

arr.select.with_index(1) { |e, i| i.odd? }
#=> [1, "bar", 9]

n- , Swoveland :

n = 2
arr.select.with_index(1) { |e, i| (i % n).zero? }
#=> [1, "bar", 9]
+2

:

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

arr.each_with_index do |value,index|
  # Do something... for example:
  otherArr <<  arr[i] if i.even?
end
+1

each_with_index map.

arr = [1, 'foo', 'bar', 'baz', 9]
arr.each_with_index.map { |i,k| i if k.odd? }.compact
#=> ["foo", "baz"]

values_at

arr.values_at(*(1..arr.size).step(2)).compact
#=> ["foo", "baz"]

and for even indices

arr.values_at(*(0..arr.size).step(2))
#=> [1, "bar", 9]

(I do not consider it reasonable to do this :-))

+1
source

each_slice can be used for this situation:

arr = [1, 'foo', 'bar', 'baz', 9]
n = 2
arr.each_slice(n) { |a1, a2| p a1 }

> 1, "bar", 9

arr.each_slice(n) { |a1, a2| p a2 }

> "foo", "baz"
+1
source

Source: https://habr.com/ru/post/1538200/


All Articles