Created
December 10, 2013 02:25
-
-
Save sjwats/7884849 to your computer and use it in GitHub Desktop.
TDD Word Count - Create an object that takes a long string and returns the frequency of each word in it.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class WordTracker | |
| attr_reader :string | |
| def initialize(string) | |
| @string = string | |
| @word_hash = {} | |
| end | |
| def log_lowercase_words | |
| @words_in_string = @string.split.map.each {|word| word.downcase.to_s} | |
| end | |
| def id_unique_words | |
| @unique_words = log_lowercase_words.uniq | |
| end | |
| def count_words(word) | |
| @words_in_string.count(word) | |
| end | |
| def word_count_to_hash | |
| id_unique_words | |
| @unique_words.each do |word| | |
| @word_hash[word] = count_words(word) | |
| end | |
| @word_hash | |
| end | |
| end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| require 'rspec' | |
| require_relative 'tdd_word_count' | |
| describe WordTracker do | |
| it 'should only initialize with a string as an argument' do | |
| words = WordTracker.new('Toy boat toy boat toy boat') | |
| expect(words.string.class).to eql(String) | |
| end | |
| it 'should handle words of varying cases' do | |
| words = WordTracker.new('Toy boat toy boat toy boat') | |
| expect(words.log_lowercase_words).to eql(["toy", "boat", "toy", "boat", "toy", "boat"]) | |
| end | |
| it 'should identify each unique word in the string' do | |
| words = WordTracker.new('Toy boat toy boat toy boat') | |
| expect(words.id_unique_words).to eql(['toy', 'boat']) | |
| end | |
| it 'should count the number of times a word appears in the given string' do | |
| words = WordTracker.new('Toy boat toy boat toy boat') | |
| words.log_lowercase_words | |
| expect(words.count_words('toy')).to eql(3) | |
| end | |
| it 'should add each unique word in the string and its word count to an array' do | |
| words = WordTracker.new('Toy boat toy boat toy boat') | |
| expect(words.word_count_to_hash).to eql({"toy"=>3, "boat"=>3}) | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment