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.
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.
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.
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
The column program is designed for pretty-printing tables of data. Assuming you use bash:
ruby-script.rb | column -s $'\t' -t
精彩评论