Actions
Feature #15945
openOption to truncate in `String#ljust`, `String#rjust`, and `String#center`
Status:
Open
Assignee:
-
Target version:
-
Description
Sometimes, I need to adjust a string to an exact length: Pad if shorter, and truncate if longer. To do that, I need to combine two methods like this:
"12".ljust(5, "*")[0, 5] # => "12***"
"1234567".ljust(5, "*")[0, 5] # => "12345"
"xyz".rjust(5, "*")[-5, 5] # => "**xyz"
"stuvwxyz".rjust(5, "*")[-5, 5] # => "vwxyz"
But that is messy, and needs a bit of thinking. It becomes even harder with centering.
I request an option on String#ljust
, String#rjust
, String#center
to truncate the string when it is longer than the given length.
One way to do so may be: take a keyword :truncate
or :trunc
.
"12".ljust(5, "*", trunc: true) # => "12***"
"1234567".ljust(5, "*", trunc: true) # => "12345"
"xyz".rjust(5, "*", trunc: true) # => "**xyz"
"stuvwxyz".rjust(5, "*", trunc: true) # => "vwxyz"
"abc".center(5, "*", trunc: true) # => "*abc*"
"abcdefg".center(5, "*", trunc: true) # => "bcdef"
Another way is, when the length is negative, interpret it as truncating option.
"12".ljust(-5, "*") # => "12***"
"1234567".ljust(-5, "*") # => "12345"
"xyz".rjust(-5, "*") # => "**xyz"
"stuvwxyz".rjust(-5, "*") # => "vwxyz"
"abc".center(-5, "*") # => "*abc*"
"abcdefg".center(-5, "*") # => "bcdef"
But the second way changes the current behavior.
Actions
Like0
Like0