我发现以下代码可以解决涉及随机化的 Ruby 初学者问题。我意识到 Ruby 有一个 shuffle
方法,但是我的问题的目的是专门关于 push
的。
def shuffle arr
shuf = []
while arr.length > 0
# Randomly pick one element of the array.
rand_index = rand(arr.length)
# Now go through each item in the array,
# putting them all into new_arr except for the # randomly chosen one, which goes into shuf.
curr_index = 0
new_arr = []
arr.each do |item|
if curr_index == rand_index
shuf.push item
else
new_arr.push item
end
curr_index = curr_index + 1
end
# Replace the original array with the new, # smaller array.
puts arr.inspect
arr = new_arr
end
shuf
end
shuffle_array = [1,2,3,4,5,6,7,8,9]
shuffle(shuffle_array)
命令行的输出是:
Rick:programs rickthomas$ ruby shuffleSolution.rb
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 2, 3, 4, 5, 6, 8, 9]
[1, 2, 3, 4, 5, 8, 9]
[1, 2, 3, 4, 5, 9]
[1, 2, 3, 4, 9]
[1, 3, 4, 9]
[3, 4, 9]
[3, 9]
[3]
Rick:programs rickthomas$
从 while arr.length > 0
行来看,arr
似乎逐渐减少,我认为这是由于 push
项所致从 arr 到其他两个数组中的任何一个。为了测试这个假设,我一直在弄乱以下代码:
array1 = [1,2,3,4,5,6,7,8]
array2 = []
array3 = []
array1.each do |x|
random_num = rand(2)
if random_num == 1
array2.push x
else
array3.push x
end
puts array1.inspect
end
我预计 array1 会以与上面的 shuffle
方法类似的方式减少,但我得到的是:
Rick:programs rickthomas$ ruby socratesWork.rb
[1, 2, 3, 4, 5, 6, 7, 8]
[1, 2, 3, 4, 5, 6, 7, 8]
[1, 2, 3, 4, 5, 6, 7, 8]
[1, 2, 3, 4, 5, 6, 7, 8]
[1, 2, 3, 4, 5, 6, 7, 8]
[1, 2, 3, 4, 5, 6, 7, 8]
[1, 2, 3, 4, 5, 6, 7, 8]
[1, 2, 3, 4, 5, 6, 7, 8]
Rick:programs rickthomas$
为什么 push
会删除第一个片段中的数组项,而不是第二个片段中的数组项?我是否只是在某个地方遗漏了语法错误,或者我是否误解了有关 push
的一些更基本的内容?
我已经在 Stack Overflow 上搜索了该问题的答案,但尚未找到类似的问题。我还查看了 ruby-doc.org,但它只讨论了添加到数组,而不是将(?)项目从一个数组移动到另一个数组。
最佳答案
好吧,您将除了具有匹配索引的元素之外的所有元素推送到new_arr
。它的大小在每次迭代中都会减少 1。
关于ruby - 使用 Ruby 的 'push' 方法是否会导致该值从原始数组中删除?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15585841/