用最后一个“/”拆分字符串并捕获split的两个部分 - Ruby

时间:2013-08-30 22:20:51

标签: ruby-on-rails ruby regex string split

我有以下ruby代码,它按每个'/'拆分一个字符串,将每个拆分分配给一个变量,在最后一个'/'之后立即插入另一个字符串,然后重新加入所有这些字符串,同时将它们分配给一个变量。

    object = "uploads/video/screenshot/74/DGSCFUA_video.jpg"
    up, vid, pic, num, file = object.split('/')
    file = "#{up}/#{vid}/#{pic}/#{num}/#{file.insert(0, "mini_")}"
    p file

    >> "uploads/video/screenshot/74/mini_DGSCFUA_video.jpg"

虽然这有效,但感觉我错过了一个技巧,这不是最有效的做事方式。

是否可以在最后'/'(i.e. object.split('/')[-1])分割字符串但是捕获分割的两个部分而不仅仅是'/'之后的字符?

3 个答案:

答案 0 :(得分:5)

您正在按摩文件路径,因此请使用为该任务制作的工具:

path_to_file = "uploads/video/screenshot/74/DGSCFUA_video.jpg"

file_path, file_name = File.split(path_to_file) 
# => ["uploads/video/screenshot/74", "DGSCFUA_video.jpg"]

或者,你可以像这样分开:

file_path, file_name = File.dirname(path_to_file), File.basename(path_to_file) 
# => ["uploads/video/screenshot/74", "DGSCFUA_video.jpg"]

然后使用:

构建新路径
path_to_file = File.join(file_path, "mini_#{ file_name }") 
# => "uploads/video/screenshot/74/mini_DGSCFUA_video.jpg"

优点是,Ruby的IO类是File的祖先,它在确定路径分隔符时会考虑操作系统,因此如果代码在Windows或* nix上运行,它将做正确的事情。

  如果可能,Ruby将在不同的操作系统约定之间转换路径名。例如,在Windows系统上,文件名“/gumby/ruby/test.rb”将打开为“\ gumby \ ruby​​ \ test.rb”。在Ruby字符串中指定Windows样式的文件名时,请记住转义反斜杠:

"c:\\gumby\\ruby\\test.rb"

答案 1 :(得分:1)

我会这样 -

str = "uploads/video/screenshot/74/DGSCFUA_video.jpg"
ar = File.split(str) # => ["uploads/video/screenshot/74", "DGSCFUA_video.jpg"]
ar[-1] = ar[-1].prepend("mini_")
File.join(*ar)
# => "uploads/video/screenshot/74/mini_DGSCFUA_video.jpg"

答案 2 :(得分:1)

正则表达式可以更灵活,更可重复使用:

 s = 'uploads/video/screenshot/74/DGSCFUA_video.jpg'
 s.scan(/(.*)\/(.*)/)
 => [["uploads/video/screenshot/74", "DGSCFUA_video.jpg"]]