在rails上的ruby中删除数组的备用元素

时间:2012-09-05 04:16:04

标签: ruby-on-rails ruby arrays ruby-on-rails-3

  

可能重复:
  Odd ( or even ) entries in a Ruby array

假设我有一个以下数组

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

我想删除备用元素,以便我的o / p数组类似于

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

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

4 个答案:

答案 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}