循环遍历数组并将每个偶数项附加到新数组

时间:2017-08-23 11:38:52

标签: ruby

我正在尝试遍历数组,将所有其他项添加到新数组中。

def yes_no(arr)
  i = 0
  new_array = []
  while i != arr.size
    arr.select.each_with_index {|value , index| index.even?}
    new_array << value
    i += 1
  end
  new_array
end

代码应该按顺序返回一个包含值的新数组。为:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

它应该返回:

[1, 3, 5, 7, 9, 2, 6, 10, 8, 4]

始终采用初始数组的第一个值。我相信我的代码具有正确的逻辑,但我需要一些帮助来解决这个问题。

这是另一个例子:

 arr = ['this', 'code', 'is', 'right', 'the']
 // returns ['this', 'is', 'the', 'right', 'code']

1 个答案:

答案 0 :(得分:4)

我不确定如何修复代码,但这是获得预期结果的另一种方法:

arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

new_array = []

until arr.empty?
  new_array << arr.shift
  arr.rotate!
end

new_array
#=> [1, 3, 5, 7, 9, 2, 6, 10, 8, 4]

请注意,arr正在修改,您可能需要dup