mahatmanich
mahatmanich

Reputation: 11033

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??

Upvotes: 2

Views: 8172

Answers (3)

Paweł Dawczak
Paweł Dawczak

Reputation: 9639

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!

Upvotes: 3

victorkt
victorkt

Reputation: 14572

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)

Upvotes: 3

Arup Rakshit
Arup Rakshit

Reputation: 118289

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"

Upvotes: 4

Related Questions