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