您的位置:首页 > 编程语言 > Ruby

Get nth element of an array in Ruby?

2014-05-29 20:43 716 查看
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?

n = 2

a = ["a", "b", "c", "d"]

b = (n - 1).step(a.size - 1, n).map{ |i| a[i] }

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

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]

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]

You can use Array#select together with Enumerator#with_index:

arr.select.with_index { |e, i| i.even? }

#=> [1, "bar", 9]

Maybe it's easier to read with 1-based indices:

arr.select.with_index(1) { |e, i| i.odd? }

#=> [1, "bar", 9]

Or to find every nth element, as Cary Swoveland points out:

n = 2

arr.select.with_index(1) { |e, i| (i % n).zero? }

#=> [1, "bar", 9]

each_slice can be used nicely 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"

I like to combine each_with_index with map.

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

arr.each_with_index.map { |i,k| i if k.odd? }.compact

#=> ["foo", "baz"]

However you can also use the values_at method

for odd indexes

arr.values_at(*(1..arr.size).step(2)).compact

#=> ["foo", "baz"]

and for even indexes

arr.values_at(*(0..arr.size).step(2))

#=> [1, "bar", 9]

same thing you can do it in ruby also:

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: