Ruby,从路径+文件名获取路径

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7399882/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 04:19:33  来源:igfitidea点击:

Ruby, getting path from path+filename

rubydirectory

提问by Onetimeposter123

Programming language: Ruby 1.9

编程语言:Ruby 1.9

Problem String: C:/Test/blah.txt
to C:/Test/

问题字符串:C:/Test/blah.txt
C:/Test/

I know it's an easy question, but Google and the Ruby quickref for Filehave no solution for me.
And I have no experience with Regex.

我知道这是一个简单的问题,但 Google 和 Ruby quickref forFile对我来说没有解决方案。
而且我没有使用正则表达式的经验。

回答by Simone Carletti

Use the Ruby File.dirnamemethod.

使用 RubyFile.dirname方法。

File.dirname("C:/Test/blah.txt")
# => "C:/Test" 

回答by Twonky

More versatile would be the Ruby Pathname class:

更通用的是 Ruby Pathname 类:

require 'pathname'

pn = Pathname.new("C:/Test/blah.txt")
p pn.dirname.to_s + Pathname::SEPARATOR_LIST

which gives C:/Test/.

这给C:/Test/.