0

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?

0

2 Answers 2

3
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}"
Sign up to request clarification or add additional context in comments.

Comments

0

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.

1 Comment

i can not find the File, i output the 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"" is in views, but i need to change it in controller.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.