On Mar 23, 3:47 am, Juan Gf [email protected] wrote:
Hello, I’m newbie so I apologize if my question it’s stupid. I want to
write a program that counts how many times a word appears in a text.
Here’s another variation, just for the learning experience:
irb(main):001:0> s = “car car ice ice house ice house tree”
=> “car car ice ice house ice house tree”
irb(main):002:0> words = s.scan /\w+/
=> [“car”, “car”, “ice”, “ice”, “house”, “ice”, “house”, “tree”]
irb(main):003:0> groups = words.group_by{ |word| word }
=> {“car”=>[“car”, “car”], “ice”=>[“ice”, “ice”, “ice”],
“house”=>[“house”, “house”], “tree”=>[“tree”]}
irb(main):005:0> counted = groups.map{ |word,list|
[list.length,word] }
=> [[2, “car”], [3, “ice”], [2, “house”], [1, “tree”]]
irb(main):007:0> sorted = counted.sort_by{ |count,word| [-
count,word] }
=> [[3, “ice”], [2, “car”], [2, “house”], [1, “tree”]]
irb(main):008:0> sorted.each{ |count,word| puts “%d %s” % [ count,
word ] }
3 ice
2 car
2 house
1 tree
=> [[3, “ice”], [2, “car”], [2, “house”], [1, “tree”]]
Of course you don’t need all those intermediary variables if you don’t
want them and don’t need to debug the results along the way:
s.scan(/\w+/).group_by{|w| w }.map{|w,l| [l.length,w] }.sort_by{ |c,w|
[-c,w] }.each{ |a| puts “%d %s” % a }
But I’d really do it the way Jesús did.