class FleschKincaid::Test

Internal: Tests a block of text based on the Flesch-Kincaid readability test and returns a {Result}.

Examples

FleschKincaid::Test.new("A sentence that is long and hard to read").result

Constants

BASE
COMPRESS_VOWEL_REGEX
SENTENCE_MULTIPLIER
SENTENCE_REGEX
SYLLABLE_MULTIPLIER
VOWEL_REGEX
WORD_REGEX
Y_REGEX

Attributes

text[R]

Public Class Methods

new(text) click to toggle source
# File lib/flesch_kincaid/test.rb, line 33
def initialize(text)
  @text = text
end

Public Instance Methods

result() click to toggle source
# File lib/flesch_kincaid/test.rb, line 37
def result
  @result ||= Result.new(formula_output)
end
total_sentences() click to toggle source

The total number of sentences in {text}

Returns {Integer}

# File lib/flesch_kincaid/test.rb, line 51
def total_sentences
  text.scan(SENTENCE_REGEX).count
end
total_syllables() click to toggle source

The total number of syllables in {text}

Returns {Integer}

# File lib/flesch_kincaid/test.rb, line 58
def total_syllables
  return 1 if text.length <= 3
  text
    .downcase
    .sub(COMPRESS_VOWEL_REGEX, '')
    .sub(Y_REGEX, '')
    .scan(VOWEL_REGEX).size
end
total_words() click to toggle source

The total number of words in {text}

Returns {Integer}

# File lib/flesch_kincaid/test.rb, line 44
def total_words
  text.scan(WORD_REGEX).count
end

Private Instance Methods

formula_output() click to toggle source

Runs the Flesch Kincaid formula:

206.835 - 1.015(totalwords / totalsentences) - 84.6 (totalsyllables / total words)

Returns {Float}

# File lib/flesch_kincaid/test.rb, line 76
def formula_output
  return 0.0 if total_words == 0 || total_sentences == 0
  sentence_val = SENTENCE_MULTIPLIER * Rational(total_words, total_sentences)
  syllable_val = SYLLABLE_MULTIPLIER * Rational(total_syllables, total_words)
  (BASE - sentence_val - syllable_val).round(2)
end