Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursive directory listing using Ruby with Chinese characters in file names

Tags:

I would like to generate a list of files within a directory. Some of the filenames contain Chinese characters.

eg: [试验].Test.txt

I am using the following code:

require 'find'
dirs = ["TestDir"]
for dir in dirs
    Find.find(dir) do |path|
    if FileTest.directory?(path)
    else
        p path
    end
    end
end

Running the script produces a list of files but the Chinese characters are escaped (replaced with backslashes followed by numbers). Using the example filename above would produce:

"TestDir/[\312\324\321\351]Test.txt" instead of "TestDir/[试验].Test.txt".

How can the script be altered to output the Chinese characters?

like image 807
p h Avatar asked Nov 21 '08 17:11

p h


1 Answers

Ruby needs to know that you are dealing with unicode in your code. Set appropriate character encoding using KCODE, as below:

$KCODE = 'utf-8'

I think utf-8 is good enough for chinese characters.

like image 155
rpattabi Avatar answered Oct 01 '22 20:10

rpattabi