Issue #15945 has been reported by sawa (Tsuyoshi Sawada).

----------------------------------------
Feature #15945: Option to truncate in `String#ljust`, `String#rjust`, and `String#center`
https://bugs.ruby-lang.org/issues/15945

* Author: sawa (Tsuyoshi Sawada)
* Status: Open
* Priority: Normal
* Assignee: 
* Target version: 
----------------------------------------
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:

```ruby
"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`.

```ruby
"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.

```ruby
"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.



-- 
https://bugs.ruby-lang.org/

Unsubscribe: <mailto:ruby-core-request / ruby-lang.org?subject=unsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-core>