Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unescaping special character sequences in Ruby strings

Tags:

string

ruby

I am loading text from a file that contains a sequence like:

abc\ndef\tghi

I want to 'unescape' all special characters, e.g. to treat the \n as a newline and \t as a tab etc. instead of automatically ending up with e.g. \\n or \\t in the string.

Is there an easy way to do this?

like image 676
mydoghasworms Avatar asked Mar 13 '12 12:03

mydoghasworms


3 Answers

The text will be loaded exactly as it is in the file. If the file has the literal text \ and n instead of a newline, that is what will be loaded. If there is a known set of escapes you want to change, you could simply gsub them

line='abc\ndef\tghi'
line.gsub!('\n', "\n")
line.gsub!('\t', "\t")
like image 177
Matt Brown Avatar answered Nov 15 '22 05:11

Matt Brown


I feel like there should be some more elegant way to do this, but you could write general-purpose method to do the swapping:

def unescape(string)
  dup = string.dup
  escaped_chars = ['n', 't', 'r', 'f', 'v', '0', 'a']
  escaped_subs = {
    "n" => "\n",
    "t" => "\t",
    "r" => "\r",
    "f" => "\f",
    "v" => "\v",
    "0" => "\0",
    "a" => "\a"
  }

  pos = 0
  while pos < dup.length
    if dup[pos] == '\\' and escaped_chars.include? dup[pos + 1]
      dup[pos..(pos + 1)] = escaped_subs[dup[pos + 1]]
    end
    pos += 1
  end

  return dup
end
like image 33
Telemachus Avatar answered Nov 15 '22 03:11

Telemachus


how about YAML.unescape ?

require 'syck/encoding'
require 'yaml'

YAML.unescape("\\n")
like image 40
jtzero Avatar answered Nov 15 '22 05:11

jtzero