How about allowing ljust' and
rjust’ take an
additional parameter (which defaults to the string
" ") which specifies what it justifies with?
15.to_s.rjust(5) # → " 15"
15.to_s.rjust(5,‘0’) # → “00015”
15.to_s.rjust(5,‘blue’) # → “blu15”
What do you think?
I agree wholeheartedly. The problem is made even worse by the fact that
‘%05s’ does not pad with leading zeros. I have had to get around this
shortfall by doing things like:
foo.to_s.rjust(10).sub(/^ {,10}/,‘0’)
Not only is this not very readable, but it is also fairly inefficient.
I also find the lack of a padding string parameter very surprising since
every other language I have run across that implements padding functions
allows (or even requires) you to specify the padding string. If you don’t
believe me, do a Google search on “lpad function” and just try to find one
that doesn’t :o)
All in all, this would seem to be a real benefit to the language, is
easy to implement, and should not break any existing code.
To expedite things, I have attached a patch that unifies the three
functions (ljust, rjust, and center) and adds this functionality. The patch
can be applied to last night’s snapshot. I have performed a moderate amount
of testing on this patch and it seems OK.
One quirk: a zero-length second parameter like "'x'.ljust(10,nil)" or
“‘x’.ljust(10,‘’)” behaves like “‘x’.ljust(10)”.
A generalized "justify" function similar to the one implemented in this
patch might be a nice addition to the language too.
- Warren Brown
string.c.diff (4.26 KB)