【问题标题】:Strip the last path directory from path string in Ruby/Rails从 Ruby/Rails 中的路径字符串中去除最后一个路径目录
【发布时间】:2015-03-10 12:45:52
【问题描述】:

是否有一个简单而快速的操作,可以在不使用正则表达式的情况下,只删除 ruby​​ 中路径的目录的最后一个路径?

路径示例:

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

目前我正在使用:

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

对于has,我将永远知道id,所以我也可以使用:

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

所以我的问题是,哪个操作更快?

【问题讨论】:

  • 数组索引“-1”是最后一个元素,因此您将获得具有 [0..-1] 的整个数组。试试path.split('/')[0..-2].join('/') 还要注意它是两个点,而不是3,即[0..-2] 不是[0...-2]
  • 你也可以试试path.delete(path.split("/").last)
  • @MaxWilliams 有什么区别? 2 点和 3 点?
  • @mahatmanich 我认为三点版本只是一个错误,但事实证明它是真实的并且您正确使用它。 “两个点”也返回最后一个元素,“三个点”不返回最后一个元素。例如(0..3).to_a => [0, 1, 2, 3]、(0...3).to_a => [0, 1, 2]、["a", "b", "c", "d"][0..-1] => ["a", "b", "c", "d"]、["a", "b", "c", "d"][0...-1] => ["a", "b", "c"]。见stackoverflow.com/questions/9690801/…。感谢您帮助我发现这一点。
  • @MaxWilliams 是的,我想排除最后一个 el :-) 很高兴我们可以互相学习一些东西 :-) 刚刚发现这两个点 :-) 并且不知道 :D

标签: ruby-on-rails ruby string


【解决方案1】:

嗯,你可以使用Pathname#parent方法。

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"

【讨论】:

    【解决方案2】:

    使用Pathname 比拆分快一点。在我的机器上运行一百万次:

    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
    

    我得到了以下结果:

                  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)
    

    【讨论】:

    • 如果你知道 id 那 path.sub("/#{id}", '') 呢?
    • @mahatmanich dirname 有效.. 但它不可读,我总是使用 parent。就像cd ..
    • 为path.sub("/#{id}", '')添加了测试。
    • 感谢您还向我展示了如何对 @victorkohl 进行基准测试
    【解决方案3】:

    Pathname - split 有一个方法:

    返回数组中的目录名和基名。

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

    希望有帮助!

    【讨论】:

      猜你喜欢
      • 2017-09-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-26
      • 2011-03-11
      • 1970-01-01
      相关资源
      最近更新 更多