Use .sort! to sort the fruits array in descending (that is, reverse)
alphabetical order. You can use the combined comparison operator (like
the
example above) or an if/elsif/else statement.
Why are we adding a .sort! method as well as doing ’ fruit1 <=>
fruit2
'. It just seems like overkill to me; like we’re doing it twice.
Shouldn’t
’ fruits.sort! ’ alone accomplish sorting the fruits into alphabetical
order.
Question #3:
Can anyone show me how this would look if done with an if/elsif/else
statement?
Question #4
are if/elsif/else statements used widely in the real world of
programming?
Use .sort! to sort the fruits array in descending (that is, reverse)
alphabetical order. You can use the combined comparison operator (like
the
example above) or an if/elsif/else statement.
Why are we adding a .sort! method as well as doing ’ fruit1 <=>
fruit2
'. It just seems like overkill to me; like we’re doing it twice.
Shouldn’t
’ fruits.sort! ’ alone accomplish sorting the fruits into alphabetical
order.
What if in the future you are trying to sort an array of hashes? Or an
array of Person objects? In those cases, you have to tell ruby how to
determine when one element of the array is smaller than, equal to, or
larger than another element.
The directions told you that you had to use either the comparison
operator or an if-else construct, and because you did neither, you
needn’t have even bothered to check whether your solution was correct.
Question #3:
Can anyone show me how this would look if done with an if/elsif/else
statement?
Check the docs for Array#sort().
If you can’t find a sort method in the Array class, check the docs
for
any module that Array includes, and look in those modules for the sort
method. Then examine the definition and read the accompanying
explanation.
What does the comparison operator actually do? Write down in words
exactly what it does. An answer such as: It compares the thing on the
left to the thing on the right", is dead wrong–the comparison operator
does much more than that. Then try to use an if-then-else statement
to duplicate what you wrote down.
Question #4
are if/elsif/else statements used widely in the real world of
programming?
if-statements are one of the most important statements in programming.
Why are we adding a .sort! method as well as doing ’ fruit1 <=> fruit2
'. It just seems like overkill to me; like we’re doing it twice. Shouldn’t
’ fruits.sort! ’ alone accomplish sorting the fruits into alphabetical
order.
I do believe that the lesson would like to teach you about providing a
different comparison function to the sorting process. I.E, you can
write
fruits.sort! do |fruit1,fruit2|
fruit2<=>fruit1
end
and this spares you the need to add the call to .reverse. Look at the
output of
ri Array#sort
for a practical example. But I know nothing about the codecademy
compiler.
Carlo
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.