Class: Lara::TextUtils::Analyzer

Inherits:
Object
  • Object
show all
Defined in:
lib/lara/text_utils/analyzer.rb

Instance Method Summary collapse

Constructor Details

#initialize(text) ⇒ Analyzer

Returns a new instance of Analyzer.



4
5
6
# File 'lib/lara/text_utils/analyzer.rb', line 4

def initialize(text)
  @text = text.to_s
end

Instance Method Details

#average_word_lengthObject



24
25
26
27
28
# File 'lib/lara/text_utils/analyzer.rb', line 24

def average_word_length
  words = @text.scan(/[[:alpha:]]+/)
  return 0.0 if words.empty?
  words.sum(&:length).to_f / words.size
end

#char_countObject



16
17
18
# File 'lib/lara/text_utils/analyzer.rb', line 16

def char_count
  @text.size
end

#char_count_no_spacesObject



20
21
22
# File 'lib/lara/text_utils/analyzer.rb', line 20

def char_count_no_spaces
  @text.gsub(/\s+/, "").size
end

#lexical_densityObject



30
31
32
33
34
# File 'lib/lara/text_utils/analyzer.rb', line 30

def lexical_density
  words = @text.scan(/[[:alpha:]]+/).map(&:downcase)
  return 0.0 if words.empty?
  (words.uniq.size.to_f / words.size * 100).round(1)
end

#reading_time(wpm: 200) ⇒ Object



36
37
38
39
40
41
42
43
44
45
# File 'lib/lara/text_utils/analyzer.rb', line 36

def reading_time(wpm: 200)
  minutes = word_count.to_f / wpm
  if minutes < 1
    "#{(minutes * 60).round} seconds"
  elsif minutes < 60
    "#{minutes.round} min"
  else
    "#{(minutes / 60).round}h #{(minutes % 60).round}m"
  end
end

#sentence_countObject



12
13
14
# File 'lib/lara/text_utils/analyzer.rb', line 12

def sentence_count
  @text.scan(/[.!?]+/).size
end

#statsObject



55
56
57
58
59
60
61
62
63
64
65
# File 'lib/lara/text_utils/analyzer.rb', line 55

def stats
  {
    word_count: word_count,
    sentence_count: sentence_count,
    char_count: char_count,
    char_count_no_spaces: char_count_no_spaces,
    average_word_length: average_word_length.round(2),
    lexical_density: lexical_density,
    reading_time: reading_time
  }
end

#summary(max_length: 100) ⇒ Object



47
48
49
50
51
52
53
# File 'lib/lara/text_utils/analyzer.rb', line 47

def summary(max_length: 100)
  clean = @text.gsub(/\s+/, " ").strip
  return clean if clean.length <= max_length
  cut = clean[0...max_length]
  cut = cut[0...cut.rindex(/\s/)] || cut
  cut + "..."
end

#word_countObject



8
9
10
# File 'lib/lara/text_utils/analyzer.rb', line 8

def word_count
  @text.scan(/[[:alpha:]]+/).size
end