MonkeeSage
12/5/2007 1:58:00 PM
On Dec 5, 4:19 am, Jose <jld...@gmail.com> wrote:
> Hello,
>
> I'm trying to use printf to give a tabulated format to my output, like
> for example:
>
> printf "%20s %10s %10s", title, author, date
>
> being title, author and date string variables. The text contained in
> these variables is uft-8 encoded, and this makes printf to misalign
> the outupt. The reason is that one multi-byte char (for example, a two-
> byte char) is counted as several chars (two chars), and thus the
> number of spaces required for padding is wrongly calculated.
>
> I searched for discussions about ruby and utf8, and in general it does
> not appear as an easy issue. I read abou the String#char proxy
> introduced by rails, but I'm not using rails, and in addition I think
> it would be of no help here.
>
> Do you know any solution to my problem? The use of printf it is not a
> requisite, all what I want if to align the output in columns, without
> using "\t"
>
> Thanks in advance,
> --Jose
Unfortunately, I think you'll have to use something ugly like this...
def pad(n, s)
(" " * (n - s.unpack("U*").length)) + s
end
def padded(*elems)
out = []
for elem in elems
out << pad(elem[0], elem[1])
end
out.join(" ")
end
puts padded([20, title], [10, author], [10, date])
Regards,
Jordan