将输出格式化为每行 40 个字符长 [英] Format output to 40 characters long per line
问题描述
我对 Ruby 还很陌生,现在我已经在 Google 上搜索了几个小时.有谁知道如何将打印输出的格式设置为不超过 40 个字符?
I'm fairly new to Ruby and I've been searching Google for a few hours now. Does anyone know how to format the output of a print to be no more than 40 characters long?
例如:
我要打印的内容:
This is a simple sentence.
This simple
sentence appears
on four lines.
但我希望它的格式为:
This is a simple sentence. This simple
sentence appears on four lines.
我将原始的每一行放入一个数组中.
所以 x = ["This is a simple sentence.", "This simple", "sentence appears", "on 三行."]
我试过 x.each { |n|print n[0..40], " " }
但它似乎没有做任何事情.
I have each line of the original put into an array.
so x = ["This is a simple sentence.", "This simple", "sentence appears", "on three lines."]
I tried x.each { |n| print n[0..40], " " }
but it didn't seem to do anything.
任何帮助都会很棒!
推荐答案
方法 word_wrap
需要一个 Strind 并进行一种漂亮的打印.
The method word_wrap
expects a Strind and makes a kind of pretty print.
您的数组通过 join("
")
Your array is converted to a string with join("
")
代码:
def word_wrap(text, line_width = 40 )
return text if line_width <= 0
text.gsub(/
/, ' ').gsub(/(.{1,#{line_width}})(s+|$)/, "\1
").strip
end
x = ["This is a simple sentence.", "This simple", "sentence appears", "on three lines."]
puts word_wrap(x.join("
"))
x << 'a' * 50 #To show what happens with long words
x << 'end'
puts word_wrap(x.join("
"))
代码说明:
x.join("
"))
构建一个字符串,然后用 text.gsub(/
/, ' ')
构建一个长行.在这种特殊情况下,这两个步骤可以合并:x.join(" "))
x.join("
"))
build a string, then build one long line with text.gsub(/
/, ' ')
.
In this special case this two steps could be merged: x.join(" "))
现在魔法发生在
gsub(/(.{1,#{line_width}})(s+|$)/, "\1
")
(.{1,#{line_width}})
):取任意字符,不超过line_width
个字符.(s+|$)
:下一个字符必须是空格或行尾(换句话说:如果最后一个匹配,前一个匹配可能比line_width
字符没有空格."\1 "
:取最多 40 个字符长的字符串并以换行符结束.gsub
重复包装直到完成.(.{1,#{line_width}})
): Take any character up toline_width
characters.(s+|$)
: The next character must be a space or line end (in other words: the previous match may be shorter theline_width
if the last character is no space."\1 "
: Take the up to 40 character long string and finish it with a newline.gsub
repeat the wrapping until it is finished.
最后,我用 strip
我还添加了一个长词(50 a's).怎么了?gsub 不匹配,单词保持原样.
I added also a long word (50 a's). What happens? The gsub does not match, the word keeps as it is.
这篇关于将输出格式化为每行 40 个字符长的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!