gpt4 book ai didi

ruby - 如何从 unix 或 windows 格式的给定文件路径获取 ruby​​ 中的基本名称?

转载 作者:太空宇宙 更新时间:2023-11-04 09:11:46 25 4
gpt4 key购买 nike

我需要从我作为输入获取的文件路径解析 ruby​​ 中的基本名称。 Unix 格式在 Linux 上运行良好。

File.basename("/tmp/text.txt")

返回“文本.txt”。
但是,当我以 Windows 格式输入时:

File.basename("C:\Users\john\note.txt")

File.basename("C:\\Users\\john\\note.txt")

“C:Usersjohn\note.txt”是输出(注意 \n 是一个新行),但我没有得到“note.txt”。

在 ruby​​/rails 中有什么好的解决方案吗?

解决方案:

"C:\\test\\note.txt".split(/\\|\//).last
=> "note.txt"
"/tmp/test/note.txt".split(/\\|\//).last
=> "note.txt"

如果 Linux 文件名不包含 \,它将起作用。

最佳答案

尝试路径名:

require 'pathname'

Pathname.new('C:\Users\john\note.txt').basename
# => #<Pathname:note.txt>

Pathname docs

引用 How to get filename without extension from file path in Ruby

关于ruby - 如何从 unix 或 windows 格式的给定文件路径获取 ruby​​ 中的基本名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55070700/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com