Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I alphabetize an array ignoring case?

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.

like image 862
user2608684 Avatar asked Jul 23 '13 01:07

user2608684


People also ask

How do you put an array in alphabetical order?

JavaScript Array sort() The sort() sorts the elements of an array. The sort() overwrites the original array. The sort() sorts the elements as strings in alphabetical and ascending order.

How do you sort a string case-insensitive?

An array can be sorted in case-insensitive order using the java. util. Arrays. sort() method.

How do I arrange a string array alphabetically?

Call the Arrays. sort() function to sort the array in alphabetical order. Then call the reverseOrder() to sort the array in reverse order.


2 Answers

How about:

wordlist.sort_by { |word| word.downcase }

Or even shorter:

wordlist.sort_by(&:downcase)
like image 134
pguardiario Avatar answered Oct 21 '22 07:10

pguardiario


In general, sort_by is not efficient for keys that are simple to compute. A more efficient comparison is to use sort with a block and replace the default comparison operator <=> with casecmp

wordlist.sort { |w1, w2| w1.casecmp(w2) }

For more information about efficiency gains, consult the official Ruby documentation for the sort_by method: http://www.ruby-doc.org/core-2.1.2/Enumerable.html#method-i-sort_by

like image 38
Simon Kaczor Avatar answered Oct 21 '22 06:10

Simon Kaczor