Reputation: 75
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
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
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
Reputation: 230306
No need to involve regex
"apple".ljust(15) # => "apple "
Upvotes: 8