ruby 27 lines · 7 steps

How greedy text wrapping works in Ruby

A word-by-word packer that fills each line up to a width limit, hard-splitting words that are too long to fit.

Explained by highlit
1def wrap_text(text, width = 80)
2 raise ArgumentError, "width must be positive" unless width.positive?
3 
4 text.split(/\n/, -1).map do |paragraph|
5 lines = []
6 current = +""
7 
8 paragraph.split(/\s+/).each do |word|
9 if current.empty?
10 current << word
11 elsif current.length + 1 + word.length <= width
12 current << " " << word
13 else
14 lines << current
15 current = +word.dup
16 end
17 
18 while current.length > width
19 lines << current[0, width]
20 current = current[width..]
21 end
22 end
23 
24 lines << current unless current.empty?
25 lines.join("\n")
26 end.join("\n")
27end
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Greedy line-filling packs each word onto the current line only if it still fits the width budget.
  2. 2Preserving original line breaks means splitting on newlines first, then re-wrapping each paragraph independently.
  3. 3Words longer than the width need a separate hard-split loop, since greedy packing alone can't shrink them.

Related explainers

Share this explainer

Here's the card — post it anywhere.

How greedy text wrapping works in Ruby — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code