Insert Escape Characters

I want to replace and insert escape sequences of characters with their escape character values, also taking into account that '\' resets the escape character.

for example

"This is a \n test. Here is a \\n which represents a newline" 

What is the easiest way to achieve this in Ruby?

+1
string ruby
Oct. 31 '09 at 1:07
source share
2 answers

I assume you are talking about the following problem:

 "\\n".gsub(/\\\\/, "\\").gsub(/\\n/, "\n") # => "n" "\\n".gsub(/\\n/, "\n").gsub(/\\\\/, "\\") # => "\\\n" 

String#gsub can take an argument from a block that does the substitution.

 str.gsub(/\\(.)/) do |s| case $1 when "n" "\n" when "t" "\t" else $1 end end 

Thus, no special escape sequence is replaced by the first, and everything works as expeted.

+1
Oct 31 '09 at 12:13
source share

Do you want the opposite of this?

 puts "This is a \n test. Here is a \\n which represents a newline" 

=>

 This is a
  test.  Here is a \ n which represents a newline
0
Oct 31 '09 at 1:22
source share



All Articles