cannot keep backslash in string in ruby code

2019-08-13 09:03发布

问题:

I have a string in my ruby code which ends with a backslash:

acc.secret_key = "ASJSJJDSJFJJFFJJFJF\"
acc.save

Above is the code snippet, when I try to save it using Active record I get an error, I tried adding another slash that is

acc.secret_key = "ASJSJJDSJFJJFFJJFJF\\"
acc.save

But now I have two slashes in the DB. What am I missing? THanks a lot.

回答1:

Are you seeing this in the console? If thats the case you're just seeing the escaping not two actual backslashes.

string = "1234\\" 
# => "1234\\"
string.length 
# => 5 (if there were two \\'s the length would be 6)
string 
# => "1234\\"
puts string
# 1234\
# => nil

If you look up a record with an escaped backslash in your db console you should see one backslash.

tests_development=> select * from tests WHERE tests.id = 1;
 id |      name       |         created_at         |         updated_at         | public 
----+-----------------+----------------------------+----------------------------+--------
  1 | this is a test\ | 2013-02-05 21:44:12.339854 | 2013-02-05 21:44:12.339854 | t
(1 row)


回答2:

acc.secret_key = "ASJSJJDSJFJJFFJJFJF//".to_string
acc.save

this will push the string with the backshash into the database