nil:NilClass (NoMethodError) by a newbie

Hi there! A newbie here who would appreciate any help you can give!

I’m doing a practice test in Chris P.'s intro to programming/Ruby
book. I’m creating a method to (recursively) sort the elements in a
given array.


def sortme unsortedarray
unsortedarray = unsortedarray.delete("")
testelement = unsortedarray.last

unsortedarray.each do |x|
if testelement < x
p = unsortedarray.index(x)
unsortedarray.delete(x)
unsortedarray[p] = “”
unsortedarray.push(x)
end
if testelement > x
end
end
sortme unsortedarray
return unsortedarray
end

givenarray = [“apples”,“pears”,“oranges”,“bananas”]
puts sortme givenarray

However when i run the program, i get this error:
filename.rb:3:in sortme': undefined methodlast’ for nil:NilClass
(NoMethodError)
from filename.rb:21:in `’

Not sure what is going on with the “.last” function - any ideas?

This line:

  unsortedarray = unsortedarray.delete("")

Is not correct. Array#delete modifies the array in place and “returns
the last deleted item, or nil if no matching item is found”
(Class: Array (Ruby 2.2.0)). On the
first pass of the function, unsortedarray.delete("") finds no matches
and returns nil, and unsortedarray is then set to nil. To fix it, at
least this particular error, remove the assignment:

  unsortedarray.delete("")

A quick test of this “solution” shows that you now have an infinite
recursion problem, so you have some additional troubleshooting to do!

Ahhhh… thank you, Mike! Embarking on that additional troubleshooting
now =)