Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 为什么';t';目录存在?';如果路径以'~';?_Ruby - Fatal编程技术网

Ruby 为什么';t';目录存在?';如果路径以'~';?

Ruby 为什么';t';目录存在?';如果路径以'~';?,ruby,Ruby,我对正在发生的事感到困惑 dir = "~/Downloads" #=> "~/Downloads" `ls #{dir}` #=> "110912-font-awesome.zip\n" Dir.exist? dir #=> false 为什么会发生这种情况?因为当您使用'ls'时,您运行一个shell命令,~与shell相关(我想这是$HOME变量的快捷方式)。但是Dir.exist?是纯ruby,它对shell一无所知,所以目录不存在 不管怎样,这是有效的 Dir.

我对正在发生的事感到困惑

dir = "~/Downloads"
#=> "~/Downloads"

`ls #{dir}`
#=> "110912-font-awesome.zip\n"

Dir.exist? dir
#=> false

为什么会发生这种情况?

因为当您使用'ls'时,您运行一个shell命令,
~
与shell相关(我想这是
$HOME
变量的快捷方式)。但是
Dir.exist?
是纯ruby,它对shell一无所知,所以目录不存在

不管怎样,这是有效的

Dir.exist?(ENV['HOME'])
可以展开
~

dir = File.expand_path('~/Downloads')
#=> /home/stefan/Downloads

Dir.exist?(dir)
#=> true

@Ursus-如果不是太大的性能问题,这可能是所有ruby
文件
目录
函数都应该为您做的事情。