Help us understand the problem. What is going on with this article?

Random Ruby Quiz –– count words in a phrase

More than 5 years have passed since last update.

You will need minitest gem:

gem install minitest

Quiz: Write a program that given a phrase can count the occurrences of each word in that phrase. Your code should pass this test suite:

test_phrase.rb
gem "minitest"
require 'minitest/autorun'
require_relative 'phrase'

class PhraseTest < Minitest::Test

  def test_count_one_word
    phrase = Phrase.new("word")
    counts = {"word" => 1}
    assert_equal counts, phrase.word_count
  end

  def test_count_one_of_each
    phrase = Phrase.new("one of each")
    counts = {"one" => 1, "of" => 1, "each" => 1}
    assert_equal counts, phrase.word_count
  end

  def test_count_multiple_occurrences
    phrase = Phrase.new("one fish two fish red fish blue fish")
    counts = {"one"=>1, "fish"=>4, "two"=>1, "red"=>1, "blue"=>1}
    assert_equal counts, phrase.word_count
  end

  def test_count_everything_just_once
    phrase = Phrase.new("all the kings horses and all the kings men")
    phrase.word_count # count it an extra time
    counts = {
      "all"=>2, "the"=>2, "kings"=>2, "horses"=>1, "and"=>1, "men"=>1
    }
    assert_equal counts, phrase.word_count
  end

  def test_ignore_punctuation
    phrase = Phrase.new("car : carpet as java : javascript!!&@$%^&")
    counts = {"car"=>1, "carpet"=>1, "as"=>1, "java"=>1, "javascript"=>1}
    assert_equal counts, phrase.word_count
  end

  def test_handles_cramped_lists
    phrase = Phrase.new("one,two,three")
    counts = {"one"=>1, "two"=>1, "three" => 1}
    assert_equal counts, phrase.word_count
  end

  def test_include_numbers
    phrase = Phrase.new("testing, 1, 2 testing")
    counts = {"testing" => 2, "1" => 1, "2" => 1}
    assert_equal counts, phrase.word_count
  end

  def test_normalize_case
    phrase = Phrase.new("go Go GO")
    counts = {"go" => 3}
    assert_equal counts, phrase.word_count
  end
end

write code in phrase.rb that pass this test suite

.
├── phrase.rb
└── test_phrase.rb

You could run the test via:

ruby test_phrase.rb

Answer is in the comment.

JuanitoFatas
Hi Nice to meet you <3 Feel free to talk to me on Twitter: https://twitter.com/juanitofatas Or follow my GitHub: https://github.com どうもありがとうございます^^
https://juanitofatas.com
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away