Is there an equivalence equivalence in Ruby?

Using Ruby, how would I automatically avoid single and double quotes in some variables written to the output file. Based on PHP, I'm looking for a function like addlashes, but for Ruby, this does not seem like a simple solution.

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 
+4
source share
3 answers

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

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

For instance:

 slashed_line = %q{Here a heavily \s\l\a\s\h\e\d "string"} puts slashed_line.gsub(/['"\\\x0]/,'\\\\\0') # Here\ a heavily \\s\\l\\a\\s\\h\\e\\d \"string\" 
+5
source

There is also String # dump :

 slashed_line = %q{Here a heavily \s\l\a\s\h\e\d "string"} puts slashed_line.dump #=> "Here a heavily \\s\\l\\a\\s\\h\\e\\d \"string\"" 
+3
source

I do not know Ruby, but I know that PHP addslashes pretty outdated.

Every time you need to avoid data, it requires a different control program. HTML needs a different encoding and processing for working with databases, and each database has its own special rules.

I assume for your question that you are looking for output to a CSV file. This, again, opens up a whole fish kettle as there is no standard CSV. You will need to do some research both for what the data will do (and if it is strict ASCII, or Unicode or something else), and what format of quotes will be needed. Most CSV users use two double quotation marks to replace one double quotation mark. If you need " on your line, you write "" .

+1
source

Source: https://habr.com/ru/post/1432999/


All Articles