Alexander Shmatko Alexander Shmatko - 1 year ago 57
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:


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


How do I resolve the problem?

Answer Source

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/ { |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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download