Skip to content

Instantly share code, notes, and snippets.

@searls
Last active June 25, 2019 14:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save searls/469d044e09ea71da6bbc6ac689da7232 to your computer and use it in GitHub Desktop.
Save searls/469d044e09ea71da6bbc6ac689da7232 to your computer and use it in GitHub Desktop.

Given this program foo.rb:

require "optparse"

options = {delimiter: " "}
OptionParser.new { |op|
  op.on("-d", "--delimiter [DELIM]", "String separating columns")
}.parse!(ARGV, into: options)

puts ["a", "b"].join(options[:delimiter])

If invoked with:

$ ruby foo.rb -d "\t"

The "\t" will be escaped to "\\t" and therefore print:

a\tb

How would you make OptionParser not do this? Custom conversion seems overkill. Attempting to unescape terminal input sounds fraught.

UPDATE: Here's a graceful enough solution, use Ruby 2.5 String#undump:

require "optparse"

options = {delimiter: " "}
OptionParser.new { |op|
  op.on("-d", "--delimiter [DELIM]", "String separating columns") do |val|
    "\"#{val}\"".undump
  end
}.parse!(ARGV, into: options)

puts ["a", "b"].join(options[:delimiter])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment