Home > Back-end >  Ruby text variable with \ inside
Ruby text variable with \ inside

Time:12-16

I need to create a db record with a column with this value

query = "booster pro 12\24 v" 

but this is what stored into db column.

"booster pro 12\u0014 v"

if I try with single-quoted I get

'booster pro 12\24 v' -> "booster pro 12\\24 v"

but If I use this, I got the correct string printed.

puts 'booster 12\24 v' -> booster 12\24 v

CodePudding user response:

If I try with single-quoted I get

'booster pro 12\24 v' -> "booster pro 12\\24 v"

This is correct. You've already got the right answer.

A backslash is an escape character. When displaying escape characters in a double-quoted string, you must escape them with a backslash. That means a literal backslash is represented by two backslashes.

Two literal backslashes would be represented by four backslashes, in a double-quoted string.

Or for example, consider:

  • How would you display a newline character? Answer: "\n"
  • How would you display a backslash character, followed by an "n"? Answer: "\\n"

This behaviour is not specific to ruby.

  •  Tags:  
  • ruby
  • Related