ruby File.expand_path奇怪的行为

时间:2015-06-26 08:01:46

标签: ruby-on-rails ruby

刚遇到有关File.expand_path api的2个问题。如果有人能帮助我,我将不胜感激: - )

Ruby:2.1.5p273(2014-11-13修订版48405)[x86_64-linux] 操作系统:Ubuntu 14.04.2

1.为什么Encoding.default_internal剂量不影响File.expand_path的编码?

2.1.5 :002 > Encoding.default_internal="utf-8"
 => "utf-8" 
2.1.5 :003 > File.expand_path("/").encoding
 => #<Encoding:US-ASCII> 

2.为什么File.expand_path会返回不同的编码?

2.1.5 :007 > File.expand_path("/").encoding
 => #<Encoding:US-ASCII> 
2.1.5 :008 > File.expand_path(".").encoding
 => #<Encoding:UTF-8> 

1 个答案:

答案 0 :(得分:0)

I think that String#encoding defaults to "US-ASCII".

My guess is that String#encoding inspects the string and detects if it contains any non-ascii characters, and in that case, returns "UTF-8".

The / path obviously doesn't contain any non-ascii characters, whereas your . path depends on your code's working directory, so if you have non-ascii characters somewhere in the path to your current working directory, then String#encoding will return "UTF-8".