1

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.

Machavity
  • 30,841
  • 27
  • 92
  • 100
TafT
  • 2,764
  • 6
  • 33
  • 51
  • 1
    Are you searching for something similar to String#ljust and String#rjust? – christianblais Sep 05 '11 at 15:54
  • Yes christianblais, I could use that to pre-format my strings or call it in line. I totally overlooked that function when I was skimming through the Ruby docs. I don't know if you solution is better than d11wtq's but it should do the job in most cases. Thanks for your comment/answer. – TafT Sep 06 '11 at 08:34

1 Answers1

2

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       "
d11wtq
  • 34,788
  • 19
  • 120
  • 195
  • Perfect, `puts "%-10s" % ["bar"] # => "foo "` is what I was hoping for but thanks for giving me both ways as I am sure it will come in useful. I am still far to use to thinking in C++ streams for output & totally forgot about sprintf for C which is a much more Ruby like output system. Thanks for your answer :-) – TafT Sep 06 '11 at 08:29