简体   繁体   中英

Strip the last path directory from path string in Ruby/Rails

Is there an easy and fast operation to just strip the last path of a directory of a path in ruby without using regex?

path examples:

has="/my/to/somewhere/id"
wants="/my/to/somewhere"

Currently I am using:

path.split('/')[0...-1].join('/')

For has I will always know the id so I could also use:

path.sub("/#{id}", '')

So my question is really, which operation is faster??

Well, you can use Pathname#parent method.

require 'pathname'

Pathname.new("/my/to/somewhere/id").parent
# => #<Pathname:/my/to/somewhere>
Pathname.new("/my/to/somewhere/id").parent.to_s
# => "/my/to/somewhere"

Using Pathname is a little bit faster than split. On my machine, running a million times:

require 'benchmark'
require 'pathname'

n = 1000000
id = "id"
Benchmark.bm do |x|
  x.report("pathname: ") { n.times { Pathname("/my/to/somewhere/id").dirname.to_s } }
  x.report("split:") { n.times { "/my/to/somewhere/id".split('/')[0...-1].join('/') } }
  x.report("path.sub:") { n.times { "/my/to/somewhere/id".sub("/#{id}", '') } }
end

I have got the following results:

              user     system      total        real
pathname:   1.550000   0.000000   1.550000 (  1.549925)
split:      1.810000   0.000000   1.810000 (  1.806914)
path.sub:   1.030000   0.000000   1.030000 (  1.030306)

There is a method for Pathname - split , which:

Returns the dirname and the basename in an Array.

require 'pathname'

Pathname.new("/my/to/somewhere/id").split.first.to_s
# => "/my/to/somewhere"

Hope that helps!

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