【发布时间】:2011-11-16 00:36:46
【问题描述】:
编程语言:Ruby 1.9
问题字符串:C:/Test/blah.txt
给C:/Test/
我知道这是一个简单的问题,但 Google 和 File 的 Ruby quickref 对我没有解决方案。
而且我没有使用正则表达式的经验。
【问题讨论】:
编程语言:Ruby 1.9
问题字符串:C:/Test/blah.txt
给C:/Test/
我知道这是一个简单的问题,但 Google 和 File 的 Ruby quickref 对我没有解决方案。
而且我没有使用正则表达式的经验。
【问题讨论】:
使用 Ruby File.dirname 方法。
File.dirname("C:/Test/blah.txt")
# => "C:/Test"
【讨论】:
File.dirname("/a/b/c/d") 正确返回 /a/b/c 但 File.dirname("/a/b/c/d/")(斜杠)也返回 /a/b/c。
更通用的是 Ruby Pathname 类:
require 'pathname'
pn = Pathname.new("C:/Test/blah.txt")
p pn.dirname.to_s + Pathname::SEPARATOR_LIST
给出C:/Test/。
【讨论】: