3

可能重复:
Ruby 数组中的奇数(或偶数)条目

假设我有一个以下数组

arr = ["Value0","Value1","Value2","Value3","Value4","Value5","Value6","Value7","Value8"]

我想删除备用元素,这样我的 o/p 数组将类似于以下内容

["Value0", "Value2", "Value4", "Value6", "Value8"]

即它应该删除奇数位置的元素。

4

4 回答 4

9

我不觉得这是最快的方式,但你可以做到

>> arr.reject {|v| arr.index(v).odd?}
#=> ["Value0", "Value2", "Value4", "Value6", "Value8"]

或者

>> arr.each_slice(2).map(&:first)
#=> ["Value0", "Value2", "Value4", "Value6", "Value8"]
于 2012-09-05T04:41:57.467 回答
6
arr.reject!.with_index{|_, i| i.odd?}

或者

arr.select!.with_index{|_, i| i.even?}
于 2012-09-05T05:34:14.640 回答
2
arr = ["Value0","Value1","Value2","Value3","Value4","Value5","Value6","Value7","Value8"]
flag = false
p arr.select!{flag = !flag}
#=> ["Value0", "Value2", "Value4", "Value6", "Value8"]
于 2012-09-05T10:33:26.200 回答
0
arr1 = arr.clone
arr.each_with_index {|el,index| arr1.delete_at(index) if index % 2 > 0 }

或者

arr1 = []
arr.each_with_index {|el,index| arr1 << el if index % 2 == 0}
于 2012-09-05T04:46:11.217 回答