2016-06-12 55 views
1

我有一個字符串對的數組。 例如:[["vendors", "users"], ["jobs", "venues"]]通過數組中的字符串重命名文件?

我有一個目錄中的文件列表:

folder/ 
    -478_accounts 
    -214_vendors 
    -389_jobs 

我需要以某種方式與子陣第二值,重命名文件,所以它看起來像這樣:

folder/ 
    -478_accounts 
    -214_users 
    -389_venues 

如何解決問題?

回答

2
folder = %w| -478_accounts -214_vendors -389_jobs | 
    #=> ["-478_accounts", "-214_vendors", "-389_jobs"] 
h = [["vendors", "users"], ["jobs", "venues"]].to_h 
    #=> {"vendors"=>"users", "jobs"=>"venues"} 

r = Regexp.union(h.keys) 
folder.each { |f| File.rename(f, f.sub(r,h)) if f =~ r } 

我使用了String#sub的形式,它使用散列來進行替換。

您可能想要優化正則表達式以要求將字符串替換爲遵循下劃線並位於字符串末尾。

r =/
    (?<=_)     # match an underscore in a positive lookbehind 
    #{Regexp.union(h.keys)} # match one of the keys of `h` 
    \z      # match end of string 
    /x      # free-spacing regex definition mode 
#=>/
# (?<=_)     # match an underscore in a positive lookbehind 
# (?-mix:vendors|jobs) # match one of the keys of `h` 
# \z      # match end of string 
# /x 

您不必使用正則表達式。

keys = h.keys 
folder.each do |f| 
    prefix, sep, suffix = f.partition('_') 
    File.rename(f, prefix+sep+h[suffix]) if sep == '_' && keys.include?(suffix) 
end 
相關問題