Patrick Gates
Patrick Gates

Reputation: 391

Tab issues in Ruby when outputting to a Shell Prompt

I have a ruby script, that when called from a shell prompt, accepts some parameters, then pulls some info from a database, then outputs that info to the prompt. I added a tab (\t) between each piece of database info, to try and make it like a table, with columns and rows, and some of it lines up correctly, but not always. How can I fix this?

Thank you.

Upvotes: 2

Views: 1426

Answers (4)

glenn jackman
glenn jackman

Reputation: 246744

The column program is designed for pretty-printing tables of data. Assuming you use bash:

ruby-script.rb | column -s $'\t' -t

Upvotes: 0

Ray Baxter
Ray Baxter

Reputation: 3200

You can solve this by formatted printing using printf statements. This gives you control over how each column is printed, how wide it is, how to treat data that is too long for the column, etc. This can be reasonably tedious if you haven't done it before in another c-like language. See the documentation for sprintf: http://ruby-doc.org/core/classes/Kernel.html#M001432

Upvotes: 1

Yossi
Yossi

Reputation: 12090

Use ljust method of string:

print 'column 1'.ljust(20)
print 'column 2'

Will print:

column 1            column 2

But this won't work for longer fields. To deal with them you can either detect the longest field or trim the content.

Upvotes: 5

Ray Toal
Ray Toal

Reputation: 88378

This is because in most terminal (or shell or console or CLI) windows, the meaning of the tab is to go to the next column from the sequence 1, 9, 17, 25, 33, 41, etc.

If you have two rows, say, like this

ABCDEFGHIJ\tKLM
ABC\tDEF

Then things will not line up because the tab in the first row jumps to column 17 but the tab in the second row causes a jump to column 9.

EDIT: I forgot to answer "how to fix this". Well, it's hard and can only be done if you know the maximum length of any column. If you do, you can output "the right number of tabs" between fields. Depends on your data.

Upvotes: 1

Related Questions