sharataka
sharataka

Reputation: 5132

How to find the frequency of 2 word combination in string using ruby?

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

Upvotes: 0

Views: 181

Answers (2)

AJcodez
AJcodez

Reputation: 34166

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}

Upvotes: 1

user1454117
user1454117

Reputation:

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

Upvotes: 0

Related Questions