11
$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/

4

2 に答える 2

24

使用できます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"
于 2012-08-23T14:26:07.713 に答える
4

後読みパターンがニーズに一致します。

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

my_path "A/B/C/D/CSS/filename"  # => CSS/filename
于 2012-08-23T14:28:21.487 に答える