简体   繁体   English

在Ruby中获取数组的第n个元素?

[英]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... 不幸的是我比Ruby更熟悉JavaScript ...

In JavaScript I could simply do 在JavaScript中我可以做到

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中做到这一点?

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] 
n = 2
a = ["a", "b", "c", "d"]
b = (n - 1).step(a.size - 1, n).map{ |i| a[i] }

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

Try above code 试试上面的代码

You can use Array#select together with Enumerator#with_index : 您可以将Array#selectEnumerator#with_index一起使用:

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

Maybe it's easier to read with 1-based indices: 也许使用基于1的索引更容易阅读:

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

Or to find every nth element, as Cary Swoveland points out : 或者找到每个第n个元素,正如Cary Swoveland指出

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

same thing you can do it in ruby also: 你也可以在ruby中做同样的事情:

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

I like to combine each_with_index with map . 我喜欢将each_with_indexmap结合起来。

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 但是,您也可以使用values_at方法

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]

(I don't consider it wise to do that :-) ) (我不认为这样做是明智的:-))

each_slice can be used nicely for this situation: each_slice可以很好地用于这种情况:

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"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM