Ruby CSV中的转义特定字符
我试图在Ruby中为CSV逃避一些特定的字符。字符为+-@=。以下是我迄今为止所做的工作:Ruby CSV中的转义特定字符,ruby,csv,Ruby,Csv,我试图在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 |conta
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
如何转义这些特定字符?请定义“转义”。旁注:
/[=|@+|-]/
是一个与四个字符和垂直条匹配的regexp。您需要[=@+-]
。我看不到您的代码中有错误。如果您只想在字符前添加\的话,我觉得一切都很好。如果这不是目标,请更具体地说明你希望它做什么,它现在正在做什么
Areth\@\+\=1 Fr\@nklin\-1