Search code examples
ruby-on-railsrubyslash

cannot keep backslash in string in ruby code


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.


Solution

  • 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)