views:

544

answers:

3

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?

+3  A: 

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.

nik
There is a printf and sprintf that use the C arguments to format a string. They are methods on Kernal (effectively built-in). See http://www.ruby-doc.org/core/classes/Kernel.html#M005962.
Kathy Van Stone
printf("%-10s %10s", args) did the trick... Thanks alot!
predhme
A: 

You typically don't want to use tabs, you want to use spaces and essentially setup your "columns" your self or else you run into these types of problems.

ThaDon
+2  A: 

Provided you know the maximum length to be no more than 20 characters:

printf "%-20s %s\n", value_name, value

If you want to make it more dynamic, something like this should work nicely:

longest_key = data_hash.keys.max { |a, b| a.length <=> b.length }
data_hash.each do |key, value|
  printf "%-#{longest_key.length}s %s\n", key, value
end
Lars Haugseth
Very nice trick! I will keep that for the future!
predhme