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