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