Alexander Shmatko Alexander Shmatko - 5 months ago 9
Ruby Question

Renaming files by string from array?

I have an array of string pairs.
For example:

[["vendors", "users"], ["jobs", "venues"]]


I have a list of files within a directory:

folder/
-478_accounts
-214_vendors
-389_jobs


I need somehow to rename files with the second value from subarrays so it would look like this:

folder/
-478_accounts
-214_users
-389_venues


How do I resolve the problem?

Answer

This is the essence of an answer. I assume you know how to step through the files in a folder and rename files.

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)
  #=> /vendors|jobs/ 
folder.map { |f| f.sub(r,h) }
  #=> ["-478_accounts", "-214_users", "-389_venues"] 

Here I've used the form of String#sub that employs a hash to make the substitution.

Comments