Ruby max宽度输出

时间:2011-09-27 04:56:13

标签: ruby

我有一个字符串数组,我需要通过空格连接打印,每行只显示每行最多80个字符(包括空格)。

例如,如果我有:

str_ary = ["I", "am", "an", "array", "of", "strings"]
max_width = 10

我应该获得:

I am an
array of  
strings

3 个答案:

答案 0 :(得分:2)

这是你的意思吗?

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

输出:

foo bar baz
quux moomin
snufkin
fred

答案 1 :(得分:0)

words = %w(foo bar baz quux moomin snufkin fred)

假设max_length是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"]]

答案 2 :(得分:0)

这将考虑空间:

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