简体   繁体   中英

Striping last directory from path with regex in Ruby?

I have a list of documents that I've collected using Dir.glob in Rails 3.

The result is a list of paths similar to the following:

/home/danny/nurserotas/GREEN WEEK 2ND JAN 2012.xls

What I would like to achieve is striping everything up, and including, the last forward slash. So the result for the above path is:

GREEN WEEK 2ND JAN 2012.xls

I'm going to be using these as links so I'm not sure if replacing the spaces with %20 is a good idea or not.

Any help would be appreciated!

Most crude way:

path = /home/danny/nurserotas/GREEN WEEK 2ND JAN 2012.xls
path.split('/').last # => GREEN WEEK 2ND JAN 2012.xls

This can also be done: File.basename(path)

This is the way I'd recommend.

File.basename("/home/danny/nurserotas/GREEN WEEK 2ND JAN 2012.xls")

As a bonus, if you need to strip off any extension:

File.basename("/home/danny/nurserotas/GREEN WEEK 2ND JAN 2012.xls", ".*")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM