1

I'm working through Learning to Program with Ruby and I am stuck on building my own sort method.

I'm struggling to figure out why the comparison method inside my recursive_sort is throwing out an error

chapter10.rb:120:in `block in recursive_sort': undefined method `<' for ["zebra"]:Array (NoMethodError)

But this works just fine...

lowest = 'zebra'
if 'cat' < 'zebra'
    lowest = 'cat'
end
puts lowest

Could someone put in the right direction to something that can help me wrap my head around this? Thanks!

puts 'Sorting Program with recursion v1.0'

# Keep two more lists around
# One for already-sorted words
# One for still - unsorted words
# Find the smallest word in the unsorted list
# push it into the end of the sorted_array

def sort some_array
    recursive_sort some_array, []
end

def recursive_sort unsorted_array, sorted_array
    lowest = unsorted_array[0]
    unsorted_array.each do |uns|
        if uns < lowest
            lowest = uns
        end
    end
    puts lowest
end

# Get a list of unsorted words into an array
orig_array = []
word = 'placeholder'
puts 'Enter a list of words to be sorted. Press enter when done.'
while word != ''
    word = gets.chomp
    orig_array.push [word]
end
orig_array.pop

puts 'This is the output of the built in sort method.'
orig_array.sort.each do |un|
    puts un
end

puts 'This is the output of Rick\'s sort method.'
sort orig_array

1 Answer 1

2
orig_array.push [word]

Here, you are actually pushing an array into an array, so that your orig_array becomes

[["word 1"], ["word 2"], ["word 3"], ...]

Remove the [] around word to fix this, or change the .push to += or .concat, which will glue together the two arrays.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.