Click here to Skip to main content
15,890,717 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Im new to ruby, and have chosen a self learning course for expanding on current languages. I bought a book but the examples are so vague and badly written that you can pull nothing use full from copying them.

guys, below is a script for opening a file spliting the words and hashing them. then displaying how many times each word appears

words = File.open('my_text.txt') {|f| f.read }.split
freqs=Hash.new(0)
words.each { |word| freqs[word] += 1 }
freqs.sort_by {|x,y| y }.reverse.each {|w, f| puts w+' '+f.to_s}

what im trying to achieve is finding the 'longest' word in this txt file, i just cant seem to do it, any suggestions or a point in the right direction please?

example from my book:

longest = %w{ cat sheep bear }.inject do |memo,word| memo.length > word.length ? memo : word

end

cannot put the hash into this, have tried multiple ways, it just throws errors
Posted

1 solution

solved:
was a bit more obvious than i thought, 2 frikkin days it took me to work out that you can load the file, split the paragrahs/words and then sort them.....

VB
longest = File.open('my_text.txt') {|f| f.read }.split.inject do |memo,word| memo.length > word.length ? memo : word
end
longest



Next issue is to add some reg ex to filter out symbols

regards
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900