From: Ryan Davis Date: 2010-03-24T08:27:37+09:00 Subject: Re: sort elements On Mar 23, 2010, at 03:35 , Juan Gf wrote: > Ryan Davis wrote: >> On Mar 23, 2010, at 02:47 , Juan Gf wrote: >> >>> 2 car >>> 1 apple >>> 1 tree >>> >>> Any ideas? >> >> Read aloud what the code says, translated to natural language (English >> or otherwise, doesn't matter... just raise it to human thought level). > a = 'Apple car caR house tree ice ice ice house' > b = a.downcase.split(' ') > b.uniq.each do |element| > puts "#{b.count(element)}\t#{element}" > end > CONVERT THE TEXT IN LOWER-CASE AND THEN SPLIT THE TEXT INTO SINGLE > [a list of] WORDS! THEN COUNT [and print] HOW MANY TIMES EVERY SINGLE WORD APPEARS! I'd say that is mostly correct. You're glossing over the uniq part: Then walk over each unique word and print how many times it occurs in the list of words. >> Then say aloud what you want it to do, step by step. > > CONVERT THE TEXT IN LOWER-CASE AND THEN SPLIT THE TEXT INTO [a list of] SINGLE WORDS! THEN COUNT HOW MANY TIMES EVERY SINGLE WORD APPEARS! THEN SORT > [the list] THE RESULTS: FIRST THE MORE COMMON WORDS AND AFTER THE LESS COMMON WORDS better. >> What's the difference? > > the difference is "THEN SORT THE RESULTS: FIRST THE MORE COMMON WORDS > AND AFTER THE LESS COMMON WORDS FINALLY BLOODY COMPUTER BRING ME A > PIZZA!" > >> Translate that difference back down to code. > > I tried to use .sort like this: > > "b.uniq.each do |element| > puts "#{(b.count(element)).sort}\t#{element}" > end" > > but obviously it doesn't work. see how I modified your description to "THEN SORT [the list]"? That's what you're missing. You're not paying attention to what your each is iterating over. As others have pointed out, there are a lot of ways to do this, my favorite is to change the description to: Convert the text to lower-case and split into a list of words. Create a hash to count the words (default to 0). Enumerate the list of words and increment the hash by one for every word seen. Enumerate the hash sorted by the word counts (descending) and name (ascending) and print the word and occurances. input = 'Apple car caR house tree ice ice ice house' count = Hash.new 0 input.downcase.split(' ').each do |word| count[word] += 1 end count.sort_by { |word, count| [-count, word] }.each do |word, count| puts "%4d: %s" % [count, word] end which outputs: 3: ice 2: car 2: house 1: apple 1: tree