【发布时间】:2013-11-23 03:16:58
【问题描述】:
所以我是编程新手,我正在研究 Chris Pine 的 Learn to Program,它教授 Ruby。我在第 10 章尝试为数组创建自己的方法。我完全不知所措,并尝试根据他建议的答案来模拟我的。摆弄之后,我无法获得输出。我运行程序,它就结束了。我什至尝试使用他的代码,但它给了我同样的问题。
这是我目前所拥有的。
unsorted_array = ['gamma', 'delta', 'beta', 'alpha', 'zeta']
sorted_array = []
def sort some_array
recursive_sort(some_array, [])
end
def recursive_sort(unsorted_array, sorted_array)
if unsorted_array.length <= 0
return sorted_array
end
still_unsorted =[]
smallest = unsorted_array.pop
sorted_array = []
unsorted_array.each do |tested_obj|
if '#{tested_obj}' > smallest
sorted_array.push(smallest)
else
still_unsorted.push(smallest)
smallest = unsorted_array.pop
end
end
recursive_sort(still_unsorted, sorted_array)
end
puts sort(recursive_sort(unsorted_array, sorted_array))
任何建议将不胜感激。
【问题讨论】:
-
当您调用
pop时,您正在改变原始数组。这是你的意图吗?