mydoghasworms
mydoghasworms

Reputation: 18591

Unescaping special character sequences in Ruby strings

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?

Upvotes: 4

Views: 2874

Answers (3)

jtzero
jtzero

Reputation: 2254

how about YAML.unescape ?

require 'syck/encoding'
require 'yaml'

YAML.unescape("\\n")

Upvotes: 1

Telemachus
Telemachus

Reputation: 19705

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

Upvotes: 1

Matt Brown
Matt Brown

Reputation: 502

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")

Upvotes: 7

Related Questions