Escaping Backslash with Ruby
Jan 14
I’ve been working with a Ruby script that inserts data into MySQL. This data can contain all sorts of weird characters and then one that recently wrecked havoc on my insert was the backslash. As you may know, under normal MySQL circumstances a single backslash (\) will need to be escaped with a double (\\). So I played around with a few regular expressions until I stumbled across one that would replace a single backslash with a double:
color = ‘blue\green’
puts color.gsub(/\\/, ‘\&\&’)
Running this script yields:
blue\\green
Ohhh the power of regular expressions. Maybe someday I’ll take the time to actually understand them. Until then I’ll continue to post snippets as a lazy reminder.
