Alexander Shmatko Alexander Shmatko - 5 months ago 11
Ruby Question

How to rename filenames using string values from hash?

I've got a directory with files:

folder/
-spider.rb
-elephant.rb
-monkey.rb


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?

folder/
-bear.rb
-rat.rb
-tiger.rb

Answer

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")
end