From: Sylvester Keil Date: 2011-11-05T19:40:16+09:00 Subject: Re: Ruby Challenge On Nov 5, 2011, at 5:59 AM, teresa nuagen wrote: > Thomas Sawyer wrote in post #1030247: >> Why does this sound like a school assignment? >> >> file = 'sample.txt' >> freq = Hash.new{|h,k| h[k] = 0} >> File.read(file).scan(/\w+/) do |w| >> freq[w] += 1 >> end >> freq.each do |w,c| >> puts "#{c} #{w}" >> end >> >> Untested. > > > There should be an "if" / "else" statement in a looping method, to add > the word in list or word count. Careful, you don't want to annoy the people who help you. The code solves your problem admirably: paste this (don't copy the ### marks) into a file and run it, and you will get exactly the output you wanted: ### freq = Hash.new{|h,k| h[k] = 0} DATA.read.scan(/\w+/) do |w| freq[w.downcase] += 1 end freq.each.sort_by {|w,c| [c,w] }.each do |w,c| puts "#{c} #{w}" end __END__ If the text file contained this sentence, the output of your program would look something like this ### Before claiming a proposed solution to a 'challenge' you posted is missing something, have the decency at least to run it to see if it works. In this case, Intransition's solution sets the counter for each word to zero (this is what the first line does: if you add a word to the freq hash for the first time the counter is set to zero). The scan method is your 'looping method' and executes the block at each iteration. Finally, `freq[w.downase] += 1` increases the counter for each word. By defining, the zero default, Intransition's solution doesn't require your if/else statement. So, please, next time, instead of simply stating 'there should be an if/else statement there', how about 'cool solution! Can you explain to me why this works without an explicit if/else statement?'.