Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 654
dannymcc Avatar asked Aug 10 '12 11:08

dannymcc


2 Answers

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)

like image 136
Kashyap Avatar answered Sep 18 '22 11:09

Kashyap


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", ".*")
like image 37
evanthegrayt Avatar answered Sep 21 '22 11:09

evanthegrayt