Ordering your library [sorting]


#1

So, I don't really understand the thought process of the code.

I've written this:

def alphabetize(arr, rev=false)
arr.sort!
end

numbers = [1,2,3,4,5]
alphabetize(numbers)
puts alphabetize

and it says it's incorrect. I know that the correct one is:

def alphabetize(arr, rev=false)
arr.sort!
if rev
return arr.reverse!
else
return arr
end
end

numbers = [6,10,3,44,-5]

puts "#{alphabetize(numbers)}".

Help me understand why there needs to be:

arr.sort!
if rev
return arr.reverse!
else
return arr
end


#2

arr.sort! # Sorts array in-place i.e changes the array to be 'alphabetized'
    if rev # If 'rev' is true. which by default it's not.
       return arr.reverse! # Return The Array reversed.
    else # Otherwise (If the 'rev' boolean/param was left untouched).
       return arr # return the newly sorted array.
end

#3

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