Skip to content

Commit

Permalink
Sort output in method.
Browse files Browse the repository at this point in the history
  • Loading branch information
marnen committed Dec 14, 2011
1 parent cfb2ad4 commit 495756d
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 16 deletions.
2 changes: 1 addition & 1 deletion lib/word_counter.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ def initialize(sentences)
end

def sorted_table
count
count.to_a.sort_by! {|row| -row[1].count }
end

private
Expand Down
30 changes: 20 additions & 10 deletions spec/word_counter_spec.rb
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
require 'spec_helper'
require 'set'

describe WordCounter do
describe 'constructor' do
Expand All @@ -10,24 +11,33 @@
describe '#sorted_table' do
it 'should return a hash with an element for each unique word in the input, disregarding case' do
sentences = ['Here are some words and SOme more woRDS']
WordCounter.new(sentences).sorted_table.collect(&:first).should == %w{here are some words and more}
WordCounter.new(sentences).sorted_table.collect(&:first).to_set.should == %w{here are some words and more}.to_set
end

it 'should ignore extra spaces and punctuation' do
sentences = ['Period.', 'And several spaces, commas; and *other* stuff.']
WordCounter.new(sentences).sorted_table.collect(&:first).should == %w{period and several spaces commas other stuff}
WordCounter.new(sentences).sorted_table.collect(&:first).to_set.should == %w{period and several spaces commas other stuff}.to_set
end

it 'should record sentence numbers for each word, starting from 1' do
sentences = ['This is sentence one.', 'And Sentence Two.']
WordCounter.new(sentences).sorted_table.should == {
'this' => [1],
'is' => [1],
'sentence' => [1, 2],
'one' => [1],
'and' => [2],
'two' => [2]
}
WordCounter.new(sentences).sorted_table.to_set.should == [
['this', [1]],
['is', [1]],
['sentence', [1, 2]],
['one', [1]],
['and', [2]],
['two', [2]]
].to_set
end

it 'should return the output sorted in descending order of frequency' do
sentences = ['Twice thrice.', 'Thrice twice.', 'Thrice once.']
WordCounter.new(sentences).sorted_table.should == [
['thrice', [1, 2, 3]],
['twice' , [1, 2]],
['once', [3]]
]
end
end
end
7 changes: 2 additions & 5 deletions word_count.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,5 @@
sentences = []
ARGF.each('.') {|s| sentences << s }

frequency_table = WordCounter.count sentences
full_table = []
frequency_table.each {|key, value| full_table << [key, value.length, value.inspect] }

puts full_table.sort_by! {|row| -row[1] }.collect {|row| row.join ', '}
frequency_table = WordCounter.new(sentences).sorted_table
puts frequency_table.collect {|row| "#{row[0]}, #{row[1].count}, #{row[1]}"}

0 comments on commit 495756d

Please sign in to comment.