on bebb340 help sign in
50 lines 1.1 kB history raw
1#!/usr/bin/env ruby
3require './utils.rb'
5def fold(filename, max_width)
6 File.open(filename, 'r:utf-8') do |file|
7 # Words in this paragraph
8 paragraph = []
10 file.each_line do |line|
11 # If we encounter an empty line, we reformat and dump the current
12 # paragraph
13 if line.strip.empty?
14 puts fold_paragraph(paragraph, max_width)
15 puts
16 paragraph = []
17 # Otherwise, we append the words found in the line to the paragraph
18 else
19 paragraph.concat line.split
20 end
21 end
23 # Last paragraph
24 puts fold_paragraph(paragraph, max_width) unless paragraph.empty?
25 end
26end
28# Fold a single paragraph to the desired width
29def fold_paragraph(paragraph, max_width)
30 # Gradually build our output
31 str, *rest = paragraph
32 width = str.length
34 rest.each do |word|
35 if width + word.length + 1 <= max_width
36 str << ' ' << word
37 width += word.length + 1
38 else
39 str << "\n" << word
40 width = word.length
41 end
42 end
44 str
45end
47ARGV.each do |f|
48 t = benchmark { fold(f, 80) }
49 STDERR.puts "#{f}: #{t}"
50end