Ruby,删除部分文件路径

时间:2012-08-23 14:18:21

标签: ruby

$local_path_to_css_file = File.expand_path(filename)

给了我

A/B/C/D/CSS/filename

A/B/C/D/CSS/layouts/filename

我希望结果是:

css/filename

css/layouts/filename

删除css/之前的所有内容。

2 个答案:

答案 0 :(得分:20)

您可以使用Pathname

require 'pathname'

absolute_path = Pathname.new(File.expand_path(filename))
project_root  = Pathname.new("/A/B/C/D") # you can set up root somewhere else, e.g. at point where script starts
relative      = absolute_path.relative_path_from(project_root)

relative.to_s # => "css/filename"

答案 1 :(得分:4)

后视模式符合您的需求。

def my_path(s)
  s[/(?=CSS).*/]
end

my_path "A/B/C/D/CSS/filename"  # => CSS/filename