How would I, say, determine if the file ~/.my_proj_config
exists on any OS in Ruby?
我如何判断文件是否~/。my_proj_config在Ruby中的任何操作系统上都存在吗?
4 个解决方案
#1
19
A call to Dir.home is a OS independent way to get to the home directory for the user. You can then use it like
调用Dir。home是一种独立于操作系统的方式,可以为用户访问home目录。然后你可以像这样使用它
File.exists?(File.join(Dir.home, ".my_proj_config"))
#2
2
This works in Ruby 1.9, but note that the call to expand_path
is required on some systems (e.g. Windows):
这在Ruby 1.9中是可行的,但是请注意,在某些系统(例如Windows)上需要调用expand_path:
File.exists?( File.expand_path "~/.my_proj_config" )
#4
0
Take a look at the Pathname
class, specifically the realpath
function - This will get you the full (expanded) path to your file.
查看路径名类,特别是realpath函数——这将使您获得文件的完整(扩展)路径。
http://www.ruby-doc.org/stdlib/libdoc/pathname/rdoc/classes/Pathname.html#M001991
http://www.ruby-doc.org/stdlib/libdoc/pathname/rdoc/classes/Pathname.html M001991
You then use the File
class along with exists?
method to find out if that exists. You shouldn't need to use realpath
if you use this method, however.
然后使用File类以及exist吗?方法查找是否存在。但是,如果使用此方法,则不需要使用realpath。
http://www.ruby-doc.org/core/classes/File.html#M000045
http://www.ruby-doc.org/core/classes/File.html M000045
#1
19
A call to Dir.home is a OS independent way to get to the home directory for the user. You can then use it like
调用Dir。home是一种独立于操作系统的方式,可以为用户访问home目录。然后你可以像这样使用它
File.exists?(File.join(Dir.home, ".my_proj_config"))
#2
2
This works in Ruby 1.9, but note that the call to expand_path
is required on some systems (e.g. Windows):
这在Ruby 1.9中是可行的,但是请注意,在某些系统(例如Windows)上需要调用expand_path:
File.exists?( File.expand_path "~/.my_proj_config" )
#3
#4
0
Take a look at the Pathname
class, specifically the realpath
function - This will get you the full (expanded) path to your file.
查看路径名类,特别是realpath函数——这将使您获得文件的完整(扩展)路径。
http://www.ruby-doc.org/stdlib/libdoc/pathname/rdoc/classes/Pathname.html#M001991
http://www.ruby-doc.org/stdlib/libdoc/pathname/rdoc/classes/Pathname.html M001991
You then use the File
class along with exists?
method to find out if that exists. You shouldn't need to use realpath
if you use this method, however.
然后使用File类以及exist吗?方法查找是否存在。但是,如果使用此方法,则不需要使用realpath。
http://www.ruby-doc.org/core/classes/File.html#M000045
http://www.ruby-doc.org/core/classes/File.html M000045