ruby 删除文件扩展名的最佳方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20901969/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 06:20:53  来源:igfitidea点击:

best way to remove file extension

rubyfilenamesfile-extension

提问by tokhi

What is the shortest way to remove file extension? this is what I have tried:

删除文件扩展名的最短方法是什么?这是我尝试过的:

file = "/home/usr/my_file.xml"
file = File.basename(file)
file.slice! File.extname(file)   #=> my_file

回答by Arup Rakshit

Read the documentation of File::basename:

阅读以下文档File::basename

basename(file_name [, suffix] ) → base_name

Returns the last component of the filename given in file_name, which can be formed using both File::SEPARATOR and File::ALT_SEPARETOR as the separator when File::ALT_SEPARATOR is not nil. If suffixis given and present at the end of file_name, it is removed.

basename(file_name [, suffix] ) → base_name

返回 file_name 中给出的文件名的最后一部分,当 File::ALT_SEPARATOR 不为零时,可以使用 File::SEPARATOR 和 File::ALT_SEPARETOR 作为分隔符形成文件名。如果给定后缀并出现在 file_name 的末尾,则将其删除。

file = "/home/usr/my_file.xml"
File.basename(file,File.extname(file)) # => "my_file"