Hi there,
I am working my way through Chris P.'s Learn to Program, and am
currently working on a sorting method (to ask the user for a list of
words and then print them alphabetized.) He suggests that we write
this program twice–once using recursion, and once using loops. I am
currently working on the recursion program, which is the hard part for
me; using loops doesn’t really give me a problem.
I guess the real root of my problem is my inability to understand
methods and parameters. I also don’t really understand the need to
employ a wrapper…something else the book recommends. Obviously the
book’s recommendations have one-up on me, as Mr. Pine is able to write
such a program and I am not.
Here is the code I have right now, please tear it apart if necessary–
I just really want to move forward but am nto willing to look up
somebody else’s method; I think that what I am trying to do should
work, it just…doesn’t.
$input = [’’]
$unsorted_array = []
$sorted_array = []
while not $input.empty?
$input = gets.chomp
$unsorted_array.push $input
end
def recursive_sort
if $unsorted_array[0] < $unsorted_array[1]
$sorted_array.push && $unsorted_array.shift
else
$unsorted_array.push $unsorted_array[1] && $unsorted_array.shift
end
puts $sorted_array
end
recursive_sort
I keep getting a number of errors, and changing things around…I was
getting a stack overflow error for awhile, as well as an EXTREMELY
frustrating “can’t compare string to nil” error on the line comparing
unsorted_array(0) to unsorted_array(1). I don’t even know what I
changed to make it go away–and the frustrating part is that I have no
idea why my array contained a nil value in the first place…and as I
was writing this I realized it must have been the ENTER that was
returned as nil? That’s all I can think of, but now when I run the
program nothing happens at all. No errors, but no data output, either.
I would greatly appreciate any insight somebody could offer on this.
Thanks in advance!