Is there a Ruby equivalent to the C++ std::setw(int) function?

一世执手 提交于 2019-12-23 02:18:10

问题


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() for those who need a few cobwebs flow out (like me) http://www.cplusplus.com/reference/iostream/manipulators/setw/

I am using Ruby 1.8 at present so a solution compatible with that would be preferable.


回答1:


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       "


来源:https://stackoverflow.com/questions/7309931/is-there-a-ruby-equivalent-to-the-c-stdsetwint-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!