From: Martin Boese Date: 2010-03-23T19:57:34+09:00 Subject: Re: sort elements On Tue, 23 Mar 2010 19:35:02 +0900 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). > > CONVERT THE TEXT IN LOWER-CASE AND THEN SPLIT THE TEXT INTO SINGLE > WORDS! THEN COUNT HOW MANY TIMES EVERY SINGLE WORD APPEARS! > > > Then say aloud what you want it to do, step by step. > > CONVERT THE TEXT IN LOWER-CASE AND THEN SPLIT THE TEXT INTO SINGLE > WORDS! THEN COUNT HOW MANY TIMES EVERY SINGLE WORD APPEARS! THEN SORT > THE RESULTS: FIRST THE MORE COMMON WORDS AND AFTER THE LESS COMMON > WORDS FINALLY, BLOODY COMPUTER, BRING ME A PIZZA! > > > 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. > > Ryan, thanks for your time and excuse for the "pizza joke" (is a bad > joke no doubt) > I would create a new array that contains the number of elements found: b.uniq.map { |uw| [b.count(uw), uw] } => [[1, "apple"], [2, "car"], [2, "house"], [1, "tree"], [3, "ice"]] Then sort it: b.uniq.map { |uw| [b.count(uw), uw] }.sort_by { |e| e[0] } => [[1, "apple"], [1, "tree"], [2, "car"], [2, "house"], [3, "ice"]] ..finally reverse and print: b.uniq.map { |uw| [b.count(uw), uw] }.sort_by { |e| e[0] }.reverse.each{ |e| puts "#{e[0]} #{e[1]}" } 3 ice 2 house 2 car 1 tree 1 apple => [[3, "ice"], [2, "house"], [2, "car"], [1, "tree"], [1, "apple"]] Use your phone to get a pizza..