How do I alphabetize an array ignoring case?

user2608684 picture user2608684 · Jul 23, 2013 · Viewed 32.8k times · Source

I'm using Chris Pine's Learn to Program and am stumped on his relatively simple challenge to take user input in the form of a list of random words and then alphabetize them in an array. Questions about this challenge have come up before, but I haven't been able to find my specific question on SO, so I'm sorry if it's a duplicate.

puts "Here's a fun trick. Type as many words as you want (one per line) and 
I'll sort them in...ALPHABETICAL ORDER! Hold on to your hats!"
wordlist = Array.new
while (userInput = gets.chomp) != ''
   wordlist.push(userInput)
end
puts wordlist.sort

While this does the trick, I'm trying to figure out how to alphabetize the array without case-sensitivity. This is hard to wrap my head around. I learned about casecmp but that seems to be a method for comparing a specific string, as opposed to an array of strings.

So far I've been trying things like:

wordlist.to_s.downcase.to_a.sort!

which, in addition to looking bad, doesn't work for multiple reasons, including that Ruby 2.0 doesn't allow strings to be converted to arrays.

Answer

pguardiario picture pguardiario · Jul 23, 2013

How about:

wordlist.sort_by { |word| word.downcase }

Or even shorter:

wordlist.sort_by(&:downcase)