sparkle
sparkle

Reputation: 7398

Ruby text variable with \ inside

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

Upvotes: 1

Views: 60

Answers (1)

Tom Lord
Tom Lord

Reputation: 28305

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.

Upvotes: 2

Related Questions