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 に答える