rpartition, but with two parts only

Viewed 104

I have a nested path e.g. backend/docs/file.yml which I want to split into a filename (file.yml) and dir (backend/docs) variables. I wanted to do a similar assignment to the one below, but without the sep variable, which is not needed anywhere.

dir, sep, filename = params[:path].rpartition("/")

File.basename and File.dirname are not good enough, as they always treat the last string as a filename (dir in backend/docs/dir/ is treated a file, not directory).

2 Answers

This ought to do it.

path = "backend/docs/dir/file.yml"
=> "backend/docs/dir/file.yml"

dir, filename = path.rpartition("/") - ["/"] 
=> ["backend/docs/dir", "file.yml"]

As @Garrett said in the comments you can use dir, _, filename = path.rpartition('/')

also you can use the built in array method values_at and do :

dir, filename = path.rpartition('/').values_at(0, -1)
Related