From: Juozas Gaigalas Date: 2006-11-16T07:05:12+09:00 Subject: Re: Fully justified/center justified output Philip Hallstrom wrote: >> Hi, how do I go about fully justifying/center justifying output text >> in ruby? >> >> I'm guessing I have to use sprintf but I can't seem to get it working >> properly, not sure of the correct "%" characters (don't know the >> proper name for them). > > http://corelib.rubyonrails.org/classes/String.html#M001536 > > str.center(integer, padstr) => new_str > > If integer is greater than the length of str, returns a new String of > length integer with str centered and padded with padstr; otherwise, > returns str. > > "hello".center(4) #=> "hello" > "hello".center(20) #=> " hello " > "hello".center(20, '123') #=> "1231231hello12312312" > > If you're printing to terminal, you'll need to know the terminal width before use can use String#center. This is simple in Windows because cmd.exe terminal is fixed-width. In Linux and OSX this is more complicated. The easiest way I know is this: require "curses" width = Curses::cols "hello".center(width) It's not totally clear from your post if this is what you're trying to do, but if it is I hope this works you.