Question

It looks like this question has been asked by a python dev (Allowing input of Unicode escapes as command line arguments), which I think partially relates, but it doesn't fully give me a solution for my immediate problem in Ruby. I'm curious if there is a way to take escaped unicode sequences as command line arguments, assign to a variable, then have the escaped unicode be processed and displayed as normal unicode after the script runs. Basically, I want to be able to choose a unicode number, then have Ruby stick that in a filename and have the actual unicode character displayed.

Here are a few things I've noticed that cause problems:

unicode = ARGV[0] #command line argument is \u263a
puts unicode
puts unicode.inspect
=> u263a
=> "u263a"

The forward slash needed to have the string be treated as a unicode sequence gets stripped. Then, if we try adding another "\" to escape it,

unicode = ARGV[0] #command line argument is \\u263a
puts unicode
puts unicode.inspect
=> \u263a
=> "\\u263a"    

but it still won't be processed properly.

Here's some more relevant code where I'm actually trying to make this happen:

unicode   = ARGV[0]
filetype  = ARGV[1]
path = unicode + "." + filetype

File.new(path, "w")

It seems like this should be pretty simple, but I've searched and searched and cannot find a solution. I should add, I do know that supplying the hard-coded escaped unicode in a string works just fine, like File.new("\u263a.#{filetype}", "w"), but getting it from an argument/variable is what I'm having an issue with. I'm using Ruby 1.9.2.

Was it helpful?

Solution

To unescape the unicode escaped command line argument and create a new file with the user supplied unicode string in the filename, I used @mu is too short's method of using pack and unpack, like so:

filetype  = ARGV[1]
unicode   = ARGV[0].gsub(/\\u([\da-fA-F]{4})/) {|m| [$1].pack("H*").unpack("n*").pack("U*")}
path      = unicode + "." + filetype
File.new(path, "w")
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top