cannot keep backslash in string in ruby code

爱⌒轻易说出口 提交于 2019-12-11 07:21:56

问题


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



来源:https://stackoverflow.com/questions/14714081/cannot-keep-backslash-in-string-in-ruby-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!