1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
def ask_words array = [] puts 'Enter words, blank row quits.' while array[array.length - 1] != '' array.push gets.chomp end array end def sort unsorted sorted = [] while unsorted.length != 0 smallest = 0 i = 0 if unsorted[i] == nil return sorted end while i != unsorted.length if unsorted[i] < unsorted[smallest] smallest = i end i = i + 1 end sorted.push unsorted[smallest] unsorted.delete_at(smallest) end sorted end sorted_array = sort ask_words puts 'sorted: ' +sorted_array.to_s
Refactorings
No refactoring yet !
Adam
August 19, 2008, August 19, 2008 17:43, permalink
Although I understand that you are probably trying to learn the logic behind sorting, Ruby has it's own built-in sort method. So, from a refactoring point of view, all you need is something like this:
1 2 3 4 5 6 7
puts "Enter words, blank row quits." while !(line = gets.chomp).empty? (lines ||= []) << line end puts "sorted: #{lines.sort}"
onwinning.blogspot.com
August 19, 2008, August 19, 2008 18:00, permalink
Yes, that would've been easy way to do it and I already knew about built-in method.
What I really struggled with was removing specific entry from array.
Emmett
August 19, 2008, August 19, 2008 18:27, permalink
onwinning - I don't quite understand what your question is. Do you want help with a recursive sort solution, or just on cleaning up your iterative solution?
onwinning.blogspot.com
August 20, 2008, August 20, 2008 04:30, permalink
Cleaning up iterative solution would be fine.
Adam
August 20, 2008, August 20, 2008 05:21, permalink
Here is your sort algorithm refactored in a more Ruby-like fashion. Hopefully it makes it much clearer as to what is going on.
1 2 3 4 5 6
def sort(array) array.inject([]) do |sorted,element| small, large = sorted.partition { |item| item < element } (small << element) + large end end
This is exercise from Chris Pines book Learning to program. I am only starting with Ruby (or any language for that matter). My solution is intentionally made without recursion, mainly because I couldn't wrap my mind around on how to do this with recursion.
Let me know if this sort of n00b problems don't belong here.