正如@sawa 所说,问题在于需要您操作字符串的双“/”。
我能想到的最直接的解决办法是:
# removes the '/' at the beginning of the string
# and splits the string to an array
a = str.sub(/^\//, '').split('/') # => ["server", "ab", "file.html"]
# iterates through the array objects EXCEPT the last one,
# (notice three dots '...' instead of two '..'),
# and adds the missing '/'
a[0...-1].each {|s| s << '/'; s.insert(0 , '/')} # => ["/server/", "/ab/"]
a # => ["/server/", "/ab/", "file.html"]
编辑 2
跟进@mudasobwa 的概念、想法和输入,如果您知道第一个字符始终是'/',这将是迄今为止最快的解决方案(请参阅编辑的基准):
a = str[1..-1].split('/')
a << (a.pop.tap { a.map! {|s| "/#{s}/" } } )
祝你好运。
基准测试
阅读@mudasobwa 的回答后,我印象非常深刻。我想知道他的解决方案有多快......
...我很惊讶地发现,尽管他的解决方案看起来更优雅,但速度要慢得多。
我不知道为什么,但在这种情况下,使用 gsub 或 scan 的 Regexp 查找似乎比较慢。
以下是基准,供任何感兴趣的人参考(每秒迭代次数 - 数字越大越好):
require 'benchmark/ips'
str = "/server/ab/file.html"
Benchmark.ips do |b|
b.report("split") do
a = str.sub(/^\//, '').split('/')
a[0...-1].each {|s| s << '/'; s.insert(0 , '/')}
end
b.report("updated split") do
a = str[1..-1].split('/')
a[0...-1].each {|s| s << '/'; s.insert(0 , '/')}
end
b.report("scan") do
str.scan(/(?<=\/)([\w.]+)(\/)?/).map { |(val,slash)| slash ? "/#{val}/" : val }
end
b.report("gsub") do
str.gsub(/(?<=\/)([\w.]+)(\/)?/).map { |m| "#{$2 && '/'}#{m}" }
end
b.report("mudasobwa's varient") do
a = str[1..-1].split('/')
[*a[0..-2].map { |e| "/#{e}/"}, a[-1]]
end
b.report("mudasobwa's tap concept") do
a = str[1..-1].split('/')
a << (a.pop.tap { a.map! {|s| "/#{s}/" } })
end
end; nil
# results:
#
# Calculating -------------------------------------
# split 39.378k i/100ms
# updated split 45.530k i/100ms
# scan 23.910k i/100ms
# gsub 18.006k i/100ms
# mudasobwa's varient 47.389k i/100ms
# mudasobwa's tap concept
# 51.895k i/100ms
# -------------------------------------------------
# split 517.487k (± 2.9%) i/s - 2.599M
# updated split 653.271k (± 6.4%) i/s - 3.278M
# scan 268.048k (± 6.9%) i/s - 1.339M
# gsub 202.457k (± 3.2%) i/s - 1.026M
# mudasobwa's varient 656.734k (± 4.8%) i/s - 3.317M
# mudasobwa's tap concept
# 761.914k (± 3.2%) i/s - 3.840M