Rubyists,
I think a fine companion for String#ljust, String#rjust and
String#center would be String#indent.
For example:
text = <<EOT
I must go down to the sea again
The lonely sea and sky
And all I want is a tall ship
And a star to steer me by
EOT
text.indent(4) == <<EOT # -> true
I must go down to the sea again
The lonely sea and sky
And all I want is a tall ship
And a star to steer me by
EOT
text.indent("-± ") == <<EOT # -> true
-± I must go down to the sea again
-± The lonely sea and sky
-± And all I want is a tall ship
-± And a star to steer me by
EOT
Note that the above code is demonstration only; I haven’t run it.
It would probably be better in hindsight to move #ljust et al into a
separate module (StringFormat, say) with which individual objects can
be extended at will. Then more and more utility methods can be added
without bloating String.
Gavin
Gavin Sinclair wrote:
Rubyists,
I think a fine companion for String#ljust, String#rjust and
String#center would be String#indent.
It’s pretty easy to just use gsub instead:
text.gsub(/^/, " "*4)
whereas ljust, rjust, and center would require a little more work to
emulate with gsub. Or do you have more functionality in mind?
Just for the heck of it, here are some bits I use from time to time.
They might fit in some kind of string formatting library.
class String
tabs left or right by n chars, using spaces
def tab n
if n >= 0
gsub(/^/, ’ ’ * n)
else
gsub(/^ {0,#{-n}}/, “”)
end
end
preserves relative tabbing
the first non-empty line ends up with n spaces before nonspace
def tabto n
if self =~ /^( *)\S/
tab(n - $1.length)
else
self
end
end
aligns each line
def taballto n
gsub(/^ */, ’ ’ * n)
end
end
Gavin Sinclair wrote:
Rubyists,
I think a fine companion for String#ljust, String#rjust and
String#center would be String#indent.
It’s pretty easy to just use gsub instead:
text.gsub(/^/, " "*4)
whereas ljust, rjust, and center would require a little more work to
emulate with gsub. Or do you have more functionality in mind?
No more, and I realised the gsub trick just after I hit send. Ease of
implementation alone doesn’t discount an idea, though 
Just for the heck of it, here are some bits I use from time to time.
They might fit in some kind of string formatting library.
Those are good. There’s a place on the Wiki for these. Is it
StandardClassExtensions? If you don’t add them, I will (when I get
around to it).
Cheers,
Gavin
···
On Tuesday, January 14, 2003, 3:16:03 PM, Joel wrote: