我正在编写自定义 shuffle 方法作为训练练习。我们的目标是将一个数组作为输入,然后吐出一个新的数组,其中所有的值都随机打乱。似乎我已经掌握了代码的要点,但由于某种原因,我不断收到消息:“意外的 kDO_COND,期待 kEND,array.each 执行 ^ |item|”。知道我做错了什么吗?
def shuffle(array)
shuf = []
while array.length > 0
randIndex = rand(array.length)
currentIndex = 0
newArray = []
array.each do |item|
if randIndex == currentIndex
shuf.push(item)
else
newArray.push(item)
end
currentIndex = currentIndex + 1
end
array = newArray
end
shuf
end