7

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!

dannymcc
  • 3,744
  • 12
  • 52
  • 85

2 Answers2

9

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)

Kashyap
  • 4,696
  • 24
  • 26
  • Does File.basename(path) strip the file extension? – dannymcc Aug 10 '12 at 11:49
  • It won't. Checked it again :) – Kashyap Aug 10 '12 at 11:54
  • Great, thanks! Just need to work out how to strip the extension now then! – dannymcc Aug 10 '12 at 11:55
  • 1
    `File.extname` gives the extension including the '.' `File.basename(path).split('.').first` would give just the filename sans the extension. Or, if you can be sure that all the files may have only a three letter extension, `File.basename(path)[0...-4]` will also do the same although it will fail if the file has an extension that is not a 3 letter one(.jpeg/.mpeg/.mp4 etc) – Kashyap Aug 10 '12 at 12:02
7

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", ".*")
evanthegrayt
  • 71
  • 2
  • 6