Problems with understanding the code


Hello. I just successfully passed this chapter but as I am totally new to programming and the logic behind it I am not sure I fully understood the code.

My question is: since the numbers in arr get sorted AND reversed within the alphabetize method, shouldn’t the output be reversed to [3,2,1]?

Since the normal .sort! (as I did in the picture) gives [1,2,3] I’m struggling to understand why the output of alphabetize(numbers) is the same, even though I used .reverse! ?

no, given rev is false, so the array isn’t reversed

1 Like

If that was what happened then that most definitely would be the result, you just made a really good argument for that this didn’t happen, you’ve found something that you can investigate on your own

Since the printed result was sorted but not reversed the next thing to do would be to add a print in the function to find out what value rev has since that what controls whether it is reversed. (because that would tell you whether or not the reversing was executed, most likely it wasn’t or the result was discarded)

You could also sanity check your argument in a simpler piece of code:

# sort and reverse should result in [3, 2, 1] .. right?
puts [2, 3, 1].sort.reverse  # indeed: [3, 2, 1]

…Just keep digging until you find the issue. Keep in mind that your plan for what should happen is the master copy of your program, the code should conform to that.

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.