Top Level Namespace

Instance Method Summary collapse

Instance Method Details

#format_array(a, p, cutoff = 120, j = '; ') ⇒ Object

format_array.rb

Example

require 'format_array'
# default cutoff is 120 characters
format_array(['list','of','things'], 'PREFIX')

# we can specify our own, say 76
format_array(['list','of','things'], 'PREFIX', 76)


12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/format_array.rb', line 12

def format_array(a, p, cutoff=120, j='; ')
    raw = a.sort.join(j)
    tmp = "#{p}: #{raw}"

    # don't bother formatting if we're short
    if raw.length + p.length < cutoff then
        return [tmp]
    end

    # try a naive longest->shortest distribution
    lines = raw.length / cutoff
    sa = a.sort_by {|s| s.length}.reverse
    out = Array.new(12) { Array.new } # what does magic 12 mean?
    while (sa.length > lines+1) do
        0.upto(lines) { |i|
            out[i].push sa.shift
        }
    end
    0.upto(sa.length-1) { |i|
        out[i].push sa.shift
    }
    strings = out.find_all {|i| i.length > 0}.map {|i| "#{p}: " << i.join(j)}
    return strings
end