Reputation: 110960
for my app if there is one white space that is fine. But if there is 2-4 I want to replace them with   to preserve the spacing.
What's the best way to do this with rails/regex? Or something else?
Desired Output:
' ' = ' '
' ' = ' '
' ' = ' '
' ' = ' '
Upvotes: 3
Views: 3367
Reputation: 219936
Why do you need both of them converted? Why not leave one as an actual space?
Then you could just use a lookahead:
srt.gsub(/ (?= )/, ' ')
See it here in action: http://regexr.com?2vodu
Upvotes: 6
Reputation: 434685
You just need a pattern that matches 2 or more spaces, then use the block form of gsub
and look at how long the match is:
s.gsub(/ {2,}/) { ' ' * $&.length }
For example:
>> ' '.gsub(/ {2,}/) { ' ' * $&.length }
=> " "
>> (' ' * 2).gsub(/ {2,}/) { ' ' * $&.length }
=> " "
>> (' ' * 3).gsub(/ {2,}/) { ' ' * $&.length }
=> " "
>> (' ' * 11).gsub(/ {2,}/) { ' ' * $&.length }
=> " "
Upvotes: 6