Donald C.
Donald C.

Reputation: 75

How to add spaces to any given string and maintain N chars?

In Ruby using regex, I want to modify a given string that will be shorter than or exactly 15 characters, so that it is always 15 characters by adding spaces.

For example:

'apple' => 'apple(10 spaces here)'

'orange' => 'orange(9 spaces here)'

'fifteenspaceshi' => 'fifteenspaceshi'

I have tried this and it works but would regex have a more elegant solution?

x = 'apple'

x = x + ' '*(15 - x.length)

Upvotes: 1

Views: 395

Answers (3)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521073

Here is another way using a left padding trick:

padding = "               "
input = "123" + padding
puts input.chars.first(15).join

"123            "
        ^^ 12 spaces

The idea here is to concatenate a string containing 15 spaces to the right of the input string. Then, we retain the first 15 characters of that concatenated result.

Upvotes: 2

Jay Dorsey
Jay Dorsey

Reputation: 3662

I think Sergio's answer is the best based on the complexity of the question, but you can also use string formatting (sprintf) if you need more complex formatting later:

"%-15s" % "apple" # => "apple          "

Read documentation for the patterns and how to read/write them.

Upvotes: 4

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230306

No need to involve regex

"apple".ljust(15) # => "apple          "

Upvotes: 8

Related Questions