Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/powerbi/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/arduino/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 更快更干净地将字符串拆分为路径的方法_Ruby - Fatal编程技术网

Ruby 更快更干净地将字符串拆分为路径的方法

Ruby 更快更干净地将字符串拆分为路径的方法,ruby,Ruby,我有一个字符串,比如: str = "/some/path/to/some/file.ext" 结果应该是: [path, dir, file] => ["/some/path/to", "some", "file.ext"] 我当前的代码: chunks = str.split '/' => ["", "some", "path", "to", "some", "file.ext"] file = chunks.pop => "file.ext" dir = chun

我有一个字符串,比如:

str = "/some/path/to/some/file.ext"
结果应该是:

[path, dir, file]
=> ["/some/path/to", "some", "file.ext"]
我当前的代码:

chunks = str.split '/'
=> ["", "some", "path", "to", "some", "file.ext"]

file = chunks.pop
=> "file.ext"

dir = chunks.pop
=> "some"

path = chunks.join '/'
=> "/some/path/to"
但是它又丑又慢

我还尝试了正则表达式和
File.split
,但结果更糟


解决方案是什么?

使用
pathname

require 'pathname'

str = "/some/path/to/some/file.ext"

p = Pathname.new str

path, dir, file = [p.dirname.parent, p.parent.basename, p.basename].map(&:to_s)

p( [path, dir, file] )
它在所有版本上都运行良好


.

太好了,谢谢。关于这个盒子,它看起来很棒。老实说,昨天我对一些问题添加了一条评论,如果Ruby能有这样的服务,那该多好啊。有人推荐ideone,但我绝对不喜欢它。非常感谢。