class Twigg::Flesch

Class which computes an approximation of the Flesch Reading Ease metric for a given piece of English-language text.

@see {en.wikipedia.org/wiki/Flesch%E2%80%93Kincaid_readability_tests}

Public Class Methods

new(string) click to toggle source
# File lib/twigg/flesch.rb, line 7
def initialize(string)
  @string = string
end

Public Instance Methods

reading_ease() click to toggle source
# File lib/twigg/flesch.rb, line 11
def reading_ease
  # from wikipedia:
  ease = 206.835 -
    1.015 * (total_words / total_sentences.to_f) -
    84.6  * (total_syllables / total_words.to_f)

  # beware NaN values (usually caused by empty commit messages),
  # incompatible with JSON
  ease.nan? ? 206.835 : ease
end

Private Instance Methods

syllables(word) click to toggle source

Returns an approximate syllable count for `word`.

Based on: {stackoverflow.com/questions/1271918/ruby-count-syllables}

# File lib/twigg/flesch.rb, line 49
def syllables(word)
  # words of 3 letters or less count as 1 syllable; rare exceptions (eg.
  # "ion") are not handled
  return 1 if word.size <= 3

  # - ignore final es, ed, e (except for le)
  # - consecutive vowels count as one syllable
  word.
    downcase.
    gsub(/W+/, ' '). # suppress punctuation
    sub(/(?:[^laeiouy]es|ed|[^laeiouy]e)$/, '').
    sub(/^y/, '').
    scan(/[aeiouy]{1,2}/).
    size
end
total_sentences() click to toggle source

Returns approximate total count of sentences in the receiver.

# File lib/twigg/flesch.rb, line 37
def total_sentences
  @string.split(/\.+/).size
end
total_syllables() click to toggle source

Returns approximate total count of syllables in the receiever.

# File lib/twigg/flesch.rb, line 42
def total_syllables
  words.inject(0) { |memo, word| memo + syllables(word) }
end
total_words() click to toggle source

Returns approximate count of words in the receiver.

# File lib/twigg/flesch.rb, line 25
def total_words
  words.size
end
words() click to toggle source

Returns an array of “words” in the receiver. “Words” are defined as strings of consecutive “word” characters (as defined by the regex short-hand, `w`).

# File lib/twigg/flesch.rb, line 32
def words
  @words ||= @string.split(/\b/).select { |w| w.match /\w/ }
end