Module: Skap::StringUtils

Extended by:
StringUtils
Included in:
StringUtils
Defined in:
lib/skap/string_utils.rb

Overview

Manipulations with strings.

Instance Method Summary collapse

Instance Method Details

#break_by_words(paragraph, max_width) ⇒ Array<String>

Parameters:

  • paragraph (String)
  • max_width (Integer)

Returns:

  • (Array<String>)


10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/skap/string_utils.rb', line 10

def break_by_words(paragraph, max_width)
  words = paragraph.split
  parts = [[]]
  line_width = 0

  while !words.empty?
    word = words.shift
    new_line_width = (line_width == 0 ? line_width : line_width + 1) + word.size
    line_width = add_word(word, parts, new_line_width, max_width)
  end

  parts.pop if parts.last.empty?

  parts.map { |line| line.join(" ") }
end