Escaping Characters


(For all intents and purposes, this project is dead, but let us just call it "Deferred Indefinitely". Shall we?)

Problem

You need to output a string and protect non-alphanumeric characters by escaping them.

Solution

Use String#dump:

string = "Some $%^& is\nbetter left alone."
  ==>"Some $%^& is\nbetter left alone."
newstring = string.dump
  ==>""Some $%^& is\\nbetter left alone.""
exit

FIX: this is stupid.

Discussion

String#dump is a very useful method when using it with eval. When you eval you often need to protect the values of a string containing non-printing characters or "special" characters (anything you'd normally escape with a backslash, e.g. carriage returns or the backslash itself). An example of this would be when you read in a value from a file or user input and you need to eval that string in the context of a code snippet.

  sort_conf = config_file.gets
  eval <<-END
    def sort_pref
      #{sort_conf.dump}
    end
  END

One thing to note is that dump outputs the contents of your string with extra quotes around it! This means that "".dump evaluates to """". If all you want is to escape a string, you need to write a routine to call dump and then strip off the outside 2 characters (on each side). Example:

  class String
    def escape
      return self.dump[1..-2]
    end
  end

Contrast

In perl, you'd probably make use of quotemeta or use \Q in interpolated strings.

Related

TODO: LIST_OF_RELATED_ITEMS

Status: In Progress