Alexander Shmatko Alexander Shmatko - 2 years ago 71
Ruby Question

How to rename filenames using string values from hash?

I've got a directory with files:


I also have hash, containing such pairs

rename_filenames =
{ "spider" => "bear",
"elephant" => "rat",
"monkey" => "tiger" }

How can I rename files with values from the hash?


Answer Source

You can simply iterate over the hash and rename accordingly:

rename_filenames.each do |old_name, new_name|
  File.rename("folder/#{old_name}.rb", "folder/#{new_name}.rb")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download