简体   繁体   中英

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? 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 :

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.

You'll also often find File.basename and File.extname useful too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM