Home > Mobile >  Single Backslash in Ruby String
Single Backslash in Ruby String

Time:05-27

I am using ruby 2.7.5. I am trying to get ^~\& assigned to a variable. I want string with only one backslash on it. I tried different things but none of them give me the desired result.

attempt normal string
irb(main):049:0> "^~\&"
=> "^~&"

thinking one \ is escaped
irb(main):050:0> "^~\\&"
=> "^~\\&"

thinking string literal will do
irb(main):052:0> '^~\&'
=> "^~\\&"

thinking one \ is skiped on literal 
irb(main):053:0> '^~\\&'
=> "^~\\&"
 
trying how 3 backward slashes will look
irb(main):054:0> '^~\\\&'
=> "^~\\\\&"

some more attempts on how backslash works, it seems like we only get even number of back slashes
irb(main):056:0> "^~\\\&"
=> "^~\\&"
irb(main):057:0> "^~\\\\&"
=> "^~\\\\&"
irb(main):058:0> "^~\\\\\&"
=> "^~\\\\&"

same thing when we use single quote
irb(main):061:0> '^~\\&'
=> "^~\\&"
irb(main):062:0> '^~\\\&'
=> "^~\\\\&"
irb(main):063:0> '^~\\\\&'
=> "^~\\\\&"

I also looked Backslashes in single quoted strings vs. double quoted strings

as per the StackOverflow suggested, I tried their example but the results were not similar.

irb(main):055:0> 'escape using "\\"'
=> "escape using \"\\\""

so could you please help me with how can I get a string with only one backslash? Also, am I missing any string concepts?

CodePudding user response:

You've already done it correctly in your 2nd and 3rd examples. The problem is you're not checking the result properly. You're relying on the console output of your string definition which gives you an escaped string back. To see the result without the escaping, use #puts.

puts('^~\&')
^~\&
=> nil
puts("^~\\&")
^~\&
=> nil

CodePudding user response:

Use two backslashes inside single-quoted or double-quoted strings. For example:

ruby -e "s = '^~\\&'; puts s;"
^~\&

ruby -e 's = "^~\\&"; puts s;'
^~\&
  • Related