Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I sort an array alphabetically?

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}" }
like image 750
Stacca Avatar asked Mar 14 '15 16:03

Stacca


Video Answer


1 Answers

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!

like image 125
jayelm Avatar answered Oct 28 '22 20:10

jayelm