1

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?

Amit Joshi
  • 15,448
  • 21
  • 77
  • 141
gsumk
  • 809
  • 10
  • 15
  • 3
    Note that `irb` outputs its values by invoking the method `.inspect`. This causes a plain `"^~\\&"` to show two backslashes where there is only one. If you do i.e. a `"^~\\&".size`, you will see that there are only 4 characters in it. – user1934428 May 27 '22 at 06:19
  • @user1934428 that was correct, that you for clarifying for `irb` usage of `.inspect` method. – gsumk Jun 06 '22 at 20:29

2 Answers2

2

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. (It essentially runs #inspect on the value, which includes/adds the escape characters.)

To see the true result (without the escaping), use #puts.

puts('^~\&')
^~\&
=> nil
puts("^~\\&")
^~\&
=> nil
BenFenner
  • 982
  • 1
  • 6
  • 12
0

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

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

ruby -e 's = "^~\\&"; puts s;'
^~\&
Timur Shtatland
  • 12,024
  • 2
  • 30
  • 47