Ruby max width output
I have an array of st开发者_C百科rings that I need to print joined by a space in a way that each line only shows a maximum of 80 characters (including the space) per line.
So for example if I have:
str_ary = ["I", "am", "an", "array", "of", "strings"]
max_width = 10
I should obtain:
I am an
array of
strings
Is this what you mean?
words = %w(foo bar baz quux moomin snufkin fred)
max_width = 11
lines = []
until words.empty?
width = -1 # The first word needs no space before it.
line, words = words.partition do |word|
(width += word.size + 1) <= max_width
end
lines << line
end
for line in lines
puts line.join(" ")
end
Output:
foo bar baz
quux moomin
snufkin
fred
words = %w(foo bar baz quux moomin snufkin fred)
assumming max_length is 15 ..
irb(main):147:0> words.inject([[]]) do |memo, word|
irb(main):148:1* (memo.last.join(' ').length + word.length < 15) ? memo.last << word : memo << [word]
irb(main):149:1> memo
irb(main):150:1> end
=> [["foo", "bar", "baz"], ["quux", "moomin"], ["snufkin", "fred"]]
This will do it accounting for the spaces:
words = %w(this is jon doe and this is ruby)
max_width = 11
lines = ['']
words.each do |word|
if (lines.last + word).size < max_width
lines[-1] += (lines.last.empty? ? word : " #{word}")
else
lines << word
end
end
p lines
精彩评论