繁体   English   中英

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

[英]Get nth element of an array in Ruby?

我有一个简单的数组,我试图抓住数组中的每个第二项。 不幸的是我比Ruby更熟悉JavaScript ...

在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] );
}

现在我怎么能在Ruby中做到这一点?

对于

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

为了获得赔率,

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

和平均,

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

一个很好的方法是取每一对,并只选择对中的第一个:

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"] 

试试上面的代码

您可以将Array#selectEnumerator#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个元素,正如Cary Swoveland指出

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

你也可以在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

我喜欢将each_with_indexmap结合起来。

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"]

甚至索引

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

(我不认为这样做是明智的:-))

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