从 Ruby 1.9.3 读取文件名时,我看到了一些奇怪的结果。例如,使用以下测试 ruby 脚本,在包含名为“Testé.txt”的文件的文件夹中运行
#!encoding:UTF-8
def inspect_string s
puts "Source encoding: #{"".encoding}"
puts "External encoding: #{Encoding.default_external}"
puts "Name: #{s.inspect}"
puts "Encoding: #{s.encoding}"
puts "Chars: #{s.chars.to_a.inspect}"
puts "Codepoints: #{s.codepoints.to_a.inspect}"
puts "Bytes: #{s.bytes.to_a.inspect}"
end
def transform_string s
puts "Testing string #{s}"
puts s.gsub(/é/u,'TEST')
end
Dir.glob("./*.txt").each do |f|
puts RUBY_VERSION + RUBY_PLATFORM
puts "Inline string works as expected"
s = "./Testé.txt"
inspect_string s
puts transform_string s
puts "File name from Dir.glob does not"
inspect_string f
puts transform_string f
end
在 Mac OS X Lion 上,我看到以下结果:
1.9.3x86_64-darwin11.4.0
Inline string works as expected
Source encoding: UTF-8
External encoding: UTF-8
Name: "./Testé.txt"
Encoding: UTF-8
Chars: [".", "/", "T", "e", "s", "t", "é", ".", "t", "x", "t"]
Codepoints: [46, 47, 84, 101, 115, 116, 233, 46, 116, 120, 116]
Bytes: [46, 47, 84, 101, 115, 116, 195, 169, 46, 116, 120, 116]
Testing string ./Testé.txt
./TestTEST.txt
File name from Dir.glob does not
Source encoding: UTF-8
External encoding: UTF-8
Name: "./Testé.txt"
Encoding: UTF-8
Chars: [".", "/", "T", "e", "s", "t", "e", "́", ".", "t", "x", "t"]
Codepoints: [46, 47, 84, 101, 115, 116, 101, 769, 46, 116, 120, 116]
Bytes: [46, 47, 84, 101, 115, 116, 101, 204, 129, 46, 116, 120, 116]
Testing string ./Testé.txt
./Testé.txt
预期的最后一行是
./TestTEST.txt
返回的编码表明这是一个普通的 UTF-8 字符串,但任何涉及 unicode 的正则表达式转换都没有正确应用。