2016-06-12 6 views
1

私は文字列のペアの配列を持っています。 例えば:配列から文字列でファイルの名前を変更しますか?

folder/ 
    -478_accounts 
    -214_users 
    -389_venues 
:私はそれは次のようになりますので、サブアレイから第二の値を使用してファイルの名前を変更するために何らかの形で必要

folder/ 
    -478_accounts 
    -214_vendors 
    -389_jobs 

[["vendors", "users"], ["jobs", "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 
関連する問題