所以我對編程很陌生,我正在研究Chris Pine的Learn to Program,它教Ruby。我在第10章試圖爲數組創建自己的方法。我完全喪失了工作,並試圖對他的建議答案進行建模。在擺弄之後,我無法獲得輸出。我運行該程序,它只是結束。我甚至嘗試過使用他的代碼,它給了我同樣的問題。在Ruby中創建我自己的排序方法
這是我到目前爲止。
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'時,你正在改變原始數組。這是你的意圖嗎? – Phrogz