Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

completed challenge #27

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions project.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
require_relative 'word_counter'

# you can initialize and use a new WordCounter with a file
counter = WordCounter.new(File.open('speech.txt','r'))
p counter.ordered_word_count

# but you can call word_count on any file so that you
# don't have to create a new WordCount object every time you
# create a new file; you can just use the existing one
p counter.ordered_word_count(File.open('speech.txt','r'))
47 changes: 47 additions & 0 deletions word_counter.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
require 'pry'

class WordCounter
attr_accessor :file, :file_string, :word_array

# you can choose to initialize a new WordCounter
# with or without a file
def initialize(file = nil)
setup_new_file(file) unless file.nil?
end

# you can choose to pass any file into WordCounter
# and the internal state of your WordCounter
# instance will be setup to reflect your new file
def ordered_word_count(file = nil)
initialize(file) unless file.nil?

# will create a hash of counts and then transform that hash into an
# array of arrays ordered by highest count to lowest count
@word_array.each_with_object(Hash.new(0)) { |word,hash| hash[word] += 1 }
.sort_by { |key,val| val }
.reverse
end

private

# get file contents as string
def read_file
@file_string = IO.read(@file)
end

# remove non-words and set word_array
def parse_file
@file_string.gsub!(/[^a-zA-Z']/,' ')
end

def set_word_array
@word_array = @file_string.split(' ')
end

def setup_new_file(file)
@file = file
read_file
parse_file
set_word_array
end
end