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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Greedy line-filling packs each word onto the current line only if it still fits the width budget.
- 2Preserving original line breaks means splitting on newlines first, then re-wrapping each paragraph independently.
- 3Words longer than the width need a separate hard-split loop, since greedy packing alone can't shrink them.
Related explainers
php
<?php class NameParser {
Parsing a full name into components in PHP
string-parsing
arrays
normalization
Intermediate
8 steps
ruby
require "shellwords" require "open3" module Backup
Building safe shell commands in Ruby
shell-out
subprocess
command-injection
Intermediate
7 steps
ruby
class UserAgentParser BROWSERS = [ [/Edg\/([\d.]+)/, "Edge"], [/OPR\/([\d.]+)/, "Opera"],
Parsing user-agent strings in Ruby
regex
pattern-matching
lookup-tables
Intermediate
8 steps
ruby
class LogAggregator BUCKET_FORMAT = "%Y-%m-%dT%H:%M" def initialize(entries)
Bucketing log entries by the minute in Ruby
aggregation
hashing
enumerable
Intermediate
5 steps
ruby
class WeeklySignupsReport DEFAULT_WEEKS = 12 def initialize(weeks: DEFAULT_WEEKS, source: User.all)
Building a weekly signups report in Rails
service object
aggregation
group by
Intermediate
7 steps
ruby
class ApplicationController < ActionController::Base EXPERIMENTS = { checkout_button_color: %w[control blue green], onboarding_flow: %w[control streamlined]
How A/B test cohorts are assigned in Rails
a-b-testing
cookies
hashing
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/how-greedy-text-wrapping-works-in-ruby-explained-ruby-1f74/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.