Avatar

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.

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 !

A8d3f35baafdaea851914b17dae9e1fc

Adam

August 19, 2008, August 19, 2008 17:43, permalink

No rating. Login to rate!

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}"
Avatar

onwinning.blogspot.com

August 19, 2008, August 19, 2008 18:00, permalink

No rating. Login to rate!

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.

A603b733176e19e6f2b2dccec29294c0

Emmett

August 19, 2008, August 19, 2008 18:27, permalink

No rating. Login to rate!

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?

Avatar

onwinning.blogspot.com

August 20, 2008, August 20, 2008 04:30, permalink

No rating. Login to rate!

Cleaning up iterative solution would be fine.

A8d3f35baafdaea851914b17dae9e1fc

Adam

August 20, 2008, August 20, 2008 05:21, permalink

1 rating. Login to rate!

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

Your refactoring





Format Copy from initial code

or Cancel