簡體   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