假设我有一个以下数组
arr = ["Value0","Value1","Value2","Value3","Value4","Value5","Value6","Value7","Value8"]
我想删除备用元素,以便我的o / p数组类似于
["Value0", "Value2", "Value4", "Value6", "Value8"]
即它应该删除奇数位置的元素。
答案 0 :(得分:7)
我觉得这不是最快的方法,但你可以做到
>> arr.reject {|v| arr.index(v).odd?}
#=> ["Value0", "Value2", "Value4", "Value6", "Value8"]
或
>> arr.each_slice(2).map(&:first)
#=> ["Value0", "Value2", "Value4", "Value6", "Value8"]
答案 1 :(得分:6)
arr.reject!.with_index{|_, i| i.odd?}
或
arr.select!.with_index{|_, i| i.even?}
答案 2 :(得分:2)
arr = ["Value0","Value1","Value2","Value3","Value4","Value5","Value6","Value7","Value8"]
flag = false
p arr.select!{flag = !flag}
#=> ["Value0", "Value2", "Value4", "Value6", "Value8"]
答案 3 :(得分: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}