我的数组包含多个路径。我想只在数组中存储文件名。
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>
提前感谢您的帮助。
答案 0 :(得分:2)
为什么不呢?
arr.map { |file_path| File.basename(file_path) }
答案 1 :(得分:0)
你不应该逃避括号。否则他们被视为字符。请尝试以下
arr.each {|f| puts f.gsub( /\/(.+)*/, '')}