1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Random Ruby Quiz –– count words in a phrase

Last updated at Posted at 2013-08-09

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.

1
1
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?