Last active
August 29, 2015 13:58
-
-
Save cesare/9933749 to your computer and use it in GitHub Desktop.
This file contains 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
# Example Answer to http://qiita.com/jnchito/items/c4a56046be1096c19b1c | |
def count_by_word(str) | |
raise ArgumentError, 'str should be a string' unless str.is_a? String | |
str.split.reduce(Hash.new(0)) {|rs, w| rs.merge(w => rs[w] + 1) } | |
end | |
describe "count_by_word" do | |
let(:results) { count_by_word(string) } | |
context 'given a normal string' do | |
let(:string) { "no ruby no life" } | |
it { expect(results).to eq('no' => 2, 'life' => 1, 'ruby' => 1) } | |
end | |
context "given a multiple-line string" do | |
let(:string) { "no ruby no life\nwe love ruby\n" } | |
it { expect(results).to eq('no' => 2, 'life' => 1, 'ruby' => 2, 'we' => 1, 'love' => 1) } | |
end | |
context "given a string with leading or trailing spaces" do | |
let(:string) { " no ruby no life " } | |
it { expect(results).to eq('no' => 2, 'life' => 1, 'ruby' => 1) } | |
end | |
context "given an empty string" do | |
let(:string) { "" } | |
it { expect(results).to eq({}) } | |
end | |
context "given a string made up of spaces" do | |
let(:string) { " " } | |
it { expect(results).to eq({}) } | |
end | |
context "given nil" do | |
let(:string) { nil } | |
it { expect { count_by_word(string) }.to raise_error ArgumentError } | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment