Search code examples
rubyformatted

Nicely formatting output to console, specifying number of tabs


I am generating a script that is outputting information to the console. The information is some kind of statistic with a value. So much like a hash.

So one value's name may be 8 characters long and another is 3. when I am looping through outputting the information with two \t some of the columns aren't aligned correctly.

So for example the output might be as such:

long value name          14
short              12
little             13
tiny               123421
long name again          912421

I want all the values lined up correctly. Right now I am doing this:

puts "#{value_name} - \t\t #{value}"

How could I say for long names, to only use one tab? Or is there another solution?


Solution

  • There is usually a %10s kind of printf scheme that formats nicely.
    However, I have not used ruby at all, so you need to check that.


    Yes, there is printf with formatting.
    The above example should right align in a space of 10 chars.
    You can format based on your widest field in the column.

    printf ([port, ]format, arg...)

    Prints arguments formatted according to the format like sprintf. If the first argument is the instance of the IO or its subclass, print redirected to that object. the default is the value of $stdout.