1

我想知道是否有一些红宝石打印功能可以让我打印一个字符串,使其居中并用空格填充。我需要为具有不同文本的程序制作横幅,如下所示:

<!-- ======================================================================= --> 
<!--                     Whatever text is in the string....                  --> 
<!-- ======================================================================= --> 

我实际上找到了一种方法来为 <= 90 - 2 个字符的字符串执行此操作..:

len = 90
msg = "random_string" 

str = msg.center( msg.length + (len - msg.length) )
print "<!-- " + str +  "-->"

但现在我想支持消息大小可以大于 90 的可能性,如果是这样的话,我可以继续换行。如果它可以避免拆分单词,那就更好了(那里的逻辑开始变得复杂)。有什么想法,或者现有的宝石/图书馆可以做到这一点吗?

谢谢,特德

4

1 回答 1

2

修订:这是一个修订后的答案,希望这更符合您的想法。它假定您有 Unix 工具fmt来调整行的大小。这可能会在 Ruby 中通过一些工作来实现。

msg = <<MSG_END
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Nunc tincidunt libero eget justo convallis tincidunt. Curabitur
augue arcu, eleifend sit amet porttitor a, porttitor ac purus.
Vivamus non leo nulla, vel pulvinar urna. Cum sociis natoque penatibus
et magnis dis parturient montes, nascetur ridiculus mus. In at purus
risus. Maecenas imperdiet commodo turpis ullamcorper porttitor. Sed
imperdiet porta rutrum. Proin sodales lorem et dui mattis accumsan.
Etiam fermentum magna sed justo tristique commodo. Nulla at purus
in leo dignissim ultrices. Mauris tincidunt egestas nunc, sit amet
placerat mauris hendrerit at. Vestibulum at vestibulum ante.
MSG_END

cols = 60 - 9 # subtract 9 to account for the extra `<!-- ` and ` -->`

sized = `echo '#{msg}' | fmt -w #{cols}`

centered = sized.split("\n").map do |l|
   "<!-- #{l.center(cols)} -->\n"
end

puts centered

回报:

<!-- Lorem ipsum dolor sit amet, consectetur adipiscing  -->
<!--  elit.  Nunc tincidunt libero eget justo convallis  -->
<!-- tincidunt. Curabitur augue arcu, eleifend sit amet  -->
<!--  porttitor a, porttitor ac purus.  Vivamus non leo  -->
<!--    nulla, vel pulvinar urna. Cum sociis natoque     -->
<!-- penatibus et magnis dis parturient montes, nascetur -->
<!--     ridiculus mus. In at purus risus. Maecenas      -->
<!-- imperdiet commodo turpis ullamcorper porttitor. Sed -->
<!-- imperdiet porta rutrum. Proin sodales lorem et dui  -->
<!--  mattis accumsan.  Etiam fermentum magna sed justo  -->
<!-- tristique commodo. Nulla at purus in leo dignissim  -->
<!--  ultrices. Mauris tincidunt egestas nunc, sit amet  -->
<!--     placerat mauris hendrerit at. Vestibulum at     -->
<!--                  vestibulum ante.                   -->
于 2012-10-16T22:51:30.047 回答