0

I've been using the code below to find the frequency of a given word in a string using Ruby. My question is how I can adapt this to find the frequency of 2 words at a given time. As example: "baa baa baa black sheep" should return...

{"baa baa"=>2, "baa black"=>1, "black sheep"=>1}  

Code:

def count_words(string)
  words = string.split(' ')
  frequency = Hash.new(0)
  words.each { |word| frequency[word.downcase] += 1 }
  return frequency
end
4
  • There are more than 3 2-word combinations in your example above. Do you care about order?
    – squiguy
    Apr 9, 2013 at 23:38
  • What are the other 2-word combinations? I'd like most frequent first.
    – sharataka
    Apr 9, 2013 at 23:41
  • I mean the order. You can have black baa too, but that would be going backwards through the string.
    – squiguy
    Apr 9, 2013 at 23:42
  • Ah I see what you mean. I'm just trying to get forward through the string.
    – sharataka
    Apr 9, 2013 at 23:43

2 Answers 2

1
str = "baa baa baa black sheep"

count = Hash.new(0)
str.split.each_cons(2) do |words|
  count[ words.join(' ') ] += 1
end
count
# => {"baa baa"=>2, "baa black"=>1, "black sheep"=>1}
1
  • Very nice, I didn't know about each_cons
    – gmalette
    Apr 10, 2013 at 0:15
0
def count_words(string)
  words = string.downcase.split(' ')
  frequency = Hash.new(0)
  while words.size >= 2
    frequency["#{words[0]} #{words[1]}"] += 1
    words.shift
  end
  frequency
end
2
  • 1
    You should downcase before you split
    – gmalette
    Apr 10, 2013 at 0:06
  • Shouldn't it only return 1 result for "yes! yes!"?
    – user1454117
    Apr 10, 2013 at 0:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.