将输出格式化为每行 40 个字符长
我对 Ruby 相当陌生,我已经在 Google 上搜索了几个小时了。 有谁知道如何将打印输出的格式设置为不超过 40 个字符长?
例如:
我想要打印的内容:
This is a simple sentence.
This simple
sentence appears
on four lines.
但我希望它的格式为:
This is a simple sentence. This simple
sentence appears on four lines.
我将原始数据的每一行放入一个数组中。
so x = ["这是一个简单的句子。", "这个简单", "句子出现", "共三行。"]
我尝试了 x.each { |n| print n[0..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?
For example:
What I want to print:
This is a simple sentence.
This simple
sentence appears
on four lines.
But I want it formatted as:
This is a simple sentence. This simple
sentence appears on four lines.
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.
Any help would be fantastic!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
word_wrap
方法需要一个 Strind 并进行一种漂亮的打印。您的数组将通过
join("\n")
转换为字符串代码:
代码说明:
x.join("\n"))
构建一个字符串,然后使用text.gsub(/\n/, ' ')
构建一长行。在这种特殊情况下,这两个步骤可以合并:
x.join(" "))
现在神奇发生在
(.{1,#{line_width }})
):取line_width
个字符以内的任意字符。(\s+|$)
:下一个字符必须是空格或行尾(换句话说:如果最后一个字符不是空格,则前一个匹配可能会比line_width
更短)gsub
重复换行直至 最后,我删除前导和尾随空格strip
我还添加了一个长单词(50 个 a),会发生什么情况? gsub 不匹配,单词保持原样。
The method
word_wrap
expects a Strind and makes a kind of pretty print.Your array is converted to a string with
join("\n")
The code:
Code explanation:
x.join("\n"))
build a string, then build one long line withtext.gsub(/\n/, ' ')
.In this special case this two steps could be merged:
x.join(" "))
And now the magic happens with
(.{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\n"
: Take the up to 40 character long string and finish it with a newline.gsub
repeat the wrapping until it is finished.And in the end, I delete leading and trailing spaces with
strip
I added also a long word (50 a's). What happens? The gsub does not match, the word keeps as it is.
Ruby 1.9(并且效率不太高):
您的解决方案不起作用的原因是所有单个字符串都短于 40 个字符,因此
n[0..40]
始终是整个字符串。Ruby 1.9 (and not overly efficient):
The reason your solution doesn't work is that all the individual strings are shorter than 40 characters, so
n[0..40]
always is the entire string.