Sahil Rally
Sahil Rally

Reputation: 541

Replace start of line with multiple space characters in front of a String in Ruby/Rails

I am trying to append 10 spaces to a new line at the beginning of the string:

string = "\nHello"

should be changed to:

"\n           Hello"

Tried following and other ways but in vain

string.gsub!("\n", "\n(\s){10}")
#=> "\n( ){10}Hello"

and

string.gsub!("\n", "\n[\s]{10}")
#=> "\n[ ]{10}Hello"

Upvotes: 3

Views: 151

Answers (1)

Sebastián Palma
Sebastián Palma

Reputation: 33420

You could use gsub, keep the matched element and append "n" whitespaces.

string = "\nHello"
p string.gsub(/\n/) { |match| "#{match}#{' ' * 20}" }
# "\n                    Hello"

Or if you want just replace them:

string.gsub(/\n/, ' ' * 20)

If you want to limit the \n to the first character in the string, then the first argument for gsub would be \A\n.

I think the more accurate to what you were trying would be:

string.gsub(/(\n)/, "#{$1}#{' ' * 20}")

Or if knowing \n can be at any place and you just care on appending the X \s:

string.gsub(/\n/, "\n#{"\s" * 20}")

Upvotes: 5

Related Questions