为什么不“Dir.exist ?“如果一条路以‘~’开头?”

时间:2021-08-24 03:44:39

I am confused with what's going on.

我对发生的事感到困惑。

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

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

Dir.exist? dir
#=> false

Why is this happening?

为什么会这样?

2 个解决方案

#1


5  

Because when you use `ls` you run a shell command and ~ is something shell-related (I suppose it's a shortcut for $HOME variable). But Dir.exist? is pure ruby, it knows nothing about the shell so that directory doesn't exist.

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

Anyway, this works

不管怎样,这工作

Dir.exist?(ENV['HOME'])

#2


4  

File.expand_path can expand ~:

文件。expand_path可以扩大~:

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

Dir.exist?(dir)
#=> true

#1


5  

Because when you use `ls` you run a shell command and ~ is something shell-related (I suppose it's a shortcut for $HOME variable). But Dir.exist? is pure ruby, it knows nothing about the shell so that directory doesn't exist.

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

Anyway, this works

不管怎样,这工作

Dir.exist?(ENV['HOME'])

#2


4  

File.expand_path can expand ~:

文件。expand_path可以扩大~:

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

Dir.exist?(dir)
#=> true