Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an addslashes equivalent in Ruby?

Tags:

ruby

Using Ruby how would I be able to automatically escape single and double quotes in some of the variables being written to the output file. Coming from PHP I'm looking for an addslashes type function, but there doesn't seem to be a simple solution for this in Ruby.

require "csv"

def generate_array( file )
    File.open("#{file}" + "_output.txt", 'w') do |output|
        CSV.foreach(file) do |img, _, part, focus, country, loc, lat, lon, desc, link|
            output.puts("[#{lat}, #{lon}, '#{img.downcase}', '#{part}', '#{loc}', '#{focus}', '#{country}', '#{desc}', '#{link}'],")
        end
    end
end

ARGV.each do |file|
    generate_array(file)
end
like image 621
Michael Gruber Avatar asked Dec 27 '22 18:12

Michael Gruber


1 Answers

I suppose you can emulate PHP addslashes functionality with this Ruby construct:

.gsub(/['"\\\x0]/,'\\\\\0')

For example:

slashed_line = %q{Here's a heavily \s\l\a\s\h\e\d "string"}
puts slashed_line.gsub(/['"\\\x0]/,'\\\\\0')
# Here\'s a heavily \\s\\l\\a\\s\\h\\e\\d \"string\"
like image 124
raina77ow Avatar answered Jan 14 '23 03:01

raina77ow