Instructions
Create a function count_words that takes a string and returns
a hash with each word as a key and its count as the value.
- Convert words to lowercase
- Split on spaces
Example: count_words("hello world hello") returns {"hello" => 2, "world" => 1}
Hints:
- Use .downcase.split to get words
- Use .tally for counting (Ruby 2.7+)
- Or use .each_with_object({}) with incrementing
Your Code
def count_words(sentence) sentence.downcase.split.tally end
RSpec.describe "count_words" do
it "counts word frequencies" do
expect(count_words("hello world hello")).to eq({ "hello" => 2, "world" => 1 })
end
it "handles single word" do
expect(count_words("ruby")).to eq({ "ruby" => 1 })
end
it "is case insensitive" do
expect(count_words("Hello HELLO hello")).to eq({ "hello" => 3 })
end
it "handles empty string" do
expect(count_words("")).to eq({})
end
end
Results
Click "Run Tests" to see results