ckdub ckdub - 6 months ago 11
Ruby Question

Words in array deleted/popped when sorting through recursion

I am learning Ruby and recursion methods. The problem I am tackling is sorting the words in an array. My recursion methods sort the array correctly, however, every time I run the array through the method, the last word from the initial array ("word") gets deleted:

# Word sorter

def sort(some_array)
recursive_sort(some_array, [])
end

def recursive_sort(unsorted_array, sorted_array)
if unsorted_array.length <= 0
return sorted_array
end

smallest = unsorted_array.pop
unsorted = []
unsorted_array.each do |word|
if word < smallest
unsorted << smallest
smallest = word
else
unsorted << word
end
end
sorted_array << smallest
recursive_sort(unsorted,sorted_array)
end


words = ['hi', 'welcome', 'bye', 'idk', 'where', 'apples', 'bananas']
sort(words)
puts "#{words}"
sort(words)
puts "#{words}"
sort(words)
puts "#{words}"


This is the what happens to the "words" array:

["hi", "welcome", "bye", "idk", "where", "apples"]
["hi", "welcome", "bye", "idk", "where"]
["hi", "welcome", "bye", "idk"]


I've been trying to figure out why this is happening. Any thoughts?

Answer

This is happening because you're passing a reference to an object (your var words) and you're performing a mutation operation on it (pop) which is actually removing the last element of the array each time recursive_sort is called.

To fix this, you'll want to use dup in order to not mutate your original array as such:

def sort(some_array)
  given_array = some_array.dup
  recursive_sort(given_array, [])
end

More importantly, to print the output of your function you need to include the method call:

words = ['hi', 'welcome', 'bye', 'idk', 'where', 'apples', 'bananas']
puts "#{sort(words)}"
puts "#{sort(words)}"
puts "#{sort(words)}"
puts "#{sort(words)}"

=>
["apples", "bananas", "bye", "hi", "idk", "welcome", "where"]
["apples", "bananas", "bye", "hi", "idk", "welcome", "where"]
["apples", "bananas", "bye", "hi", "idk", "welcome", "where"]
["apples", "bananas", "bye", "hi", "idk", "welcome", "where"]
Comments