我有一个包含几个路径的数组。我想在数组中只存储文件名。
arr = ["/This/is/MyFirst/Path/file1","/This/is/MySecond/Path/file2","/This/is/MyThird/Path/file3"]
我试图删除所有除了文件名与gsub,但我不知道为什么我使用的正则表达式不工作,因为当我运行下面的代码时,没有删除任何东西。
arr.each {|f| puts f.gsub( //(.+)*/, '')}
这是我的测试:
irb(main):172:0* arr = ["/This/is/MyFirst/Path/file1","/This/is/MySecond/Path/file2","/This/is/MyThird/Path/file3"]
=> ["/This/is/MyFirst/Path/file1", "/This/is/MySecond/Path/file2", "/This/is/MyThird/Path/file3"]
irb(main):173:0> arr.each {|f| puts f.gsub( //(.+)*/, '')}
/This/is/MyFirst/Path/file1
/This/is/MySecond/Path/file2
/This/is/MyThird/Path/file3
=> ["/This/is/MyFirst/Path/file1", "/This/is/MySecond/Path/file2", "/This/is/MyThird/Path/file3"]
irb(main):174:0>
提前感谢您的帮助。
为什么不呢?
arr.map { |file_path| File.basename(file_path) }
不应该转义括号。否则,它们将被视为字符。试试下面的
arr.each {|f| puts f.gsub( //(.+)*/, '')}