是否有与C ++ std :: setw(int)函数等效的Ruby? [英] Is there a Ruby equivalent to the C++ std::setw(int) function?
问题描述
我正在将一些文本表输出到终端,并且希望能够使用C ++ std :: setw()函数之类的内容为我的输出提供填充,而不是猜测所需的空格或制表符的数量。在我一起做一些事情之前,已经有一个函数或Ruby Gem可以做到这一点吗?
I am outputting some text tables to a terminal and would like to be able to use something like the C++ std::setw() function to provide padding for my output rather than guessing at the number of spaces or tabs required. Before I go knock together something to do this, is there already a function or Ruby Gem which does this?
Std :: setw()用于那些需要一些蜘蛛网的人(像我一样) http://www.cplusplus.com/reference/iostream/manipulators/setw/
Std::setw() for those who need a few cobwebs flow out (like me) http://www.cplusplus.com/reference/iostream/manipulators/setw/
我目前正在使用Ruby 1.8,因此最好使用与之兼容的解决方案。
I am using Ruby 1.8 at present so a solution compatible with that would be preferable.
推荐答案
界面不一样(思路略有不同),但是如果我正确理解了目的,通常只使用 sprintf
。
It's not the same interface (so slightly different thinking), but if I understand the purpose correctly, I usually just use sprintf
for this.
puts "%10s" % ["foo"] # => " foo"
puts "%-10s" % ["bar"] # => "foo "
这篇关于是否有与C ++ std :: setw(int)函数等效的Ruby?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!