Oscar Jiang Oscar Jiang - 10 months ago 41
Ruby Question

String start with # return with backslash in rails console in some case

In console of rails 4.2.7, I have the following test:

[45] pry(main)> '#$'
=> "\#$"
[46] pry(main)> '#@'
=> "\#@"
[47] pry(main)> '#!'
=> "#!"
[48] pry(main)> '#ab'
=> "#ab"

It seems rails will only put a "\" before the string when there is an @ or $ after #.

The problem leads me to this test is that I have a erb file that render a data attribute with an array of json:

data-xx="<%= [{xx: '#$', yy: 'yy'}.to_json, {zz: 'zzz'}.to_json] %>"

Then in chrome console, it will give the unexpected result as

"["{\"xx\":\"\#$\",\"yy\":\"yy\"}", "{\"zz\":\"zzz\"}"]"

And when I change xx value from #! or some other string, the result will be ok as an array

["{"xx":"#!","yy":"yy"}", "{"zz":"zzz"}"]

Does someone know if it is true and why it has such difference?
And it there any way to tackle this problem?

Answer Source

@mudasobwa's explaination is correct

According to your situation you should try in this way

===> In rails console

 json_values = [{xx: '#$', yy: 'yy'}, {zz: 'zzz'}].to_json

===> In chrome console

 result = JSON.parse(json_values)

you will get expected array, its just ruby technique to handle string interpolation thing