[英]ruby on rails replace some string
I have two strings. 我有两个琴弦。 One is:
一种是:
"/system/musics/videos/000/000/001/original/%E5%B9%BF%E5%9C%BA%E8%88%9E%E5%BF%AB%E5%9B%9B_-_%E5%A4%A7%E8%8D%89%E5%8E%9F-%E4%BE%AF%E6%AD%8C.MP3"
The second one is: 第二个是:
"广场舞快四_-_大草原-侯歌.MP3"
I want to get: 我想得到:
"/system/musics/videos/000/000/001/original/广场舞快四_-_大草原-侯歌.MP3"
Does anyone know how to find and replace the string in ruby? 有谁知道如何在ruby中查找和替换字符串? My idea is to replace the contents after the last
'/'
with the second string. 我的想法是用第二个字符串替换最后一个
'/'
之后的内容。 How can I do it? 我该怎么做?
first_string = "/system/musics/videos/000/000/001/original/%E5%B9%BF%E5%9C%BA%E8%88%9E%E5%BF%AB%E5%9B%9B_-%E5%A4%A7%E8%8D%89%E5%8E%9F-%E4%BE%AF%E6%AD%8C.MP3"
second_string = "广场舞快四-_大草原-侯歌.MP3"
"#{File.dirname(first_string)}/#{second_string}"
When dealing with filenames, especially if there is a chance your code will be used on multiple operating systems, use the built-in filename manipulation methods dirname
and join
: 处理文件名时,尤其是如果您的代码有可能在多个操作系统上使用时,请使用内置的文件名处理方法
dirname
和join
:
File.join(
File.dirname(
"/system/musics/videos/000/000/001/original/%E5%B9%BF%E5%9C%BA%E8%88%9E%E5%BF%AB%E5%9B%9B_-_%E5%A4%A7%E8%8D%89%E5%8E%9F-%E4%BE%AF%E6%AD%8C.MP3"
),
"广场舞快四_-_大草原-侯歌.MP3"
)
The reason is, File.join
and File.dirname
are aware of filename delimiters used on a particular OS, courtesy of File::SEPARATOR
and File::ALT_SEPARATOR
, making them able to split and join the paths correctly. 原因是
File.join
和File.dirname
知道在特定操作系统上使用的文件名分隔符,这要File::ALT_SEPARATOR
File::SEPARATOR
和File::ALT_SEPARATOR
,这使它们能够正确拆分和File::ALT_SEPARATOR
路径。
You'll also often find File.basename
and File.extname
useful too. 您还会经常发现
File.basename
和File.extname
很有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.