Recursive directory listing using Ruby with Chinese characters in file names

I would like to generate a list of files in a directory. Some file names contain Chinese characters.

for example: [试验] .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 creates a list of files, but Chinese characters are escaped (replaced by backslashes followed by numbers). Using the example file name above, you will get:

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

How can I change the script to output Chinese characters?

+5
source share
2 answers

Ruby , unicode . KCODE, :

$KCODE = 'utf-8'

, utf-8 .

+4

. ( ) ( ).

Dir.entries(Dir.pwd).each do |x|
  p x.encode('UTF-8') unless FileTest.directory?(x)  
end 

, :

Dir.glob('*/*').each do |x|
  p x.encode('UTF-8') unless FileTest.directory?(x)  
end

, , Dir.glob('**/*') , .

+1

All Articles