我正在尝试将Ruby中的某些特定字符转义为CSV。字符是+-@ =。到目前为止,这是我所做的:
def self.to_csv
headers = %w{Date_de_création Civilité Nom_complet Email Téléphone Bien Agent Utilisateur}
CSV.generate(headers: true) do |csv|
csv << headers
all.each do |contact|
csv << [
contact.created_at.strftime("%d/%m/%Y"),
contact.gender,
contact.full_name, contact.email,
contact.phone,
contact.accommodation.try(:ref_agency),
contact.agent.try(:full_name) ,
contact.user.try(:full_name) ].map { |attribute| escape_characters_in_string(attribute) if attribute.present? }
end
end
end
def self.escape_characters_in_string(string)
pattern = /[=|@|+|-]/
string.gsub(pattern) {|match| "\\" + "#{match}"}
end
CSV中“ Areth @ + = 1 Fr @ nklin-1”的输出:
Areth\@\+\=1 Fr\@nklin\-1
我将如何逃脱这些特定字符?