How do I sort an array alphabetically?
Why not just change.sort
?
Array#sort
without a block defaults to ascending sort, which is the block { |a, b| a <=> b }
:
sorted = change.sort # Ascending sort
sorted = change.sort { |a, b| a <=> b } # Same thing!
sorted
# => ["cents", "coins", "dimes", "pence", "pennies", "quarters"]
Note this block needs to account for the two variables you're comparing, unlike the block you wrote in your question. Including a custom comparator is only necessary if you wish to modify the way elements are sorted, e.g. if you want to sort in descending order: { |a, b| b <=> a }
If you want to print a text representation of the array, use
puts sorted
and if you want to sort in place (not create a new arrray) use sort!