我正在试图循环访问一个数组,并将每个其他项添加到新数组中。循环访问数组并将每个偶数项添加到新数组中
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']
预期结果是什么?再次检查它,现在它很不清楚。 – Ilya
你为什么叫这个'yes_no'? –
我认为目前尚不清楚如何获得预期的结果。 _“将每个其他项目添加到一个新数组”_听起来好像结果应该简单地为'[1,3,5,7,9]'。这并不是很明显,为什么后面跟着“2,6,10,8,4”(按此顺序)。 – Stefan