简体   繁体   中英

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"

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}")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM