How do I sort an array alphabetically?

Stacca picture Stacca · Mar 14, 2015 · Viewed 21.6k times · Source

Having trouble with my syntax have tried a few things but still not getting it right. What am I not understanding? Thanks

change = ['cents', 'pennies', 'coins', 'dimes', 'pence', 'quarters']
change.sort {|anythinghere| a <=> b puts "Ascending #{anythinghere}" }

Answer

jayelm picture jayelm · Mar 14, 2015

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!