19. Sorting


Hey there :smile: I am new to code academy and would like some clarification on my code.

fruits.sort! do |fruity, frutie| frutie <=> fruity

works in this case but I don't fully understand what it reads. I wrote the code in comparison to the previous lesson. I would love your feedback! Thanks.


fruits.sort! do |fruity, frutie| frutie <=> fruity

you can view the first parameter as the "beginning" and the second one as the "end"

as you can see in this new code:

numbers = [1, 2, 3, 4, 5]

numbers.sort! do |beginning,theEnd|
theEnd <=> beginning

-----> 5 , 4 , 3 , 2 ,1

this will sort from theEnd to beginning, its that simple! And the same can be done for the alphabet

you can write the code in block form too,

fruits = ["orange", "apple", "banana", "pear", "grapes"]

fruits.sort! {|beginning,theEnd| theEnd <=> beginning}


Your code should look like this

fruits = ["orange", "apple", "banana", "pear", "grapes"]
fruits.sort! do |firstFruits, secondFruits|
secondFruits <=> firstFruits


You forgot to add end to the code.


Late reply, but thanks for the help! that makes more sense now :smile:


also recommend updating the parser to only look for the the correct result instead of the correct syntax. I understand we're trying to teach people here, but you know what works just as well.


Trying it both ways is good practice, and that it's just as important that the students understand the point of the lesson was to learn the comparator as well as the .sort method, but neither one or the other by itself. Also I'm finding that .sort works just as well as .sort!; why is that?


Best explanation I've seen! Thank you!