kareemgrant
6/14/2015 - 3:47 PM

word_counter.rb

class WordCounter
  attr_reader :words, :frequency

  def initialize(content)
    @words = content.downcase.gsub(/[.,]/, '').split(' ')
  end

  def count
    word_frequency = Hash.new(0)

    words.each do |word|
      word_frequency[word] += 1
    end

    @frequency = word_frequency.sort_by {|key, value| value }.reverse.to_h

    return @frequency
  end

  def most_frequent_word
    frequency.first[0]
  end
end

text = "Initially, Matz looked at other languages to find an ideal syntax. Recalling his search, he said, “I wanted a scripting language that was more powerful than Perl, and more object-oriented than Python.”

In Ruby, everything is an object. Every bit of information and code can be given their own properties and actions. Object-oriented programming calls properties by the name instance variables and actions are known as methods. Ruby’s pure object-oriented approach is most commonly demonstrated by a bit of code which applies an action to a number.
Ruby is a language of careful balance. Its creator, Yukihiro “Matz” Matsumoto, blended parts of his favorite languages (Perl, Smalltalk, Eiffel, Ada, and Lisp) to form a new language that balanced functional programming with imperative programming.

He has often said that he is “trying to make Ruby natural, not simple,” in a way that mirrors life.

Building on this, he adds:

Ruby is simple in appearance, but is very complex inside, just like our human body"

word_counter = WordCounter.new(text)

puts word_counter.count

puts "#{word_counter.most_frequent_word} is the most frequently used word"