ericalli
ericalli

Reputation: 1233

Creating a hash from another hash

I'm currently working with two different hashes that contain common values and I would like to normalize the hash key names.

Hash #1 looks like:

files = [{ "filename" => "file.txt","path" => "/folder/file.txt" }]

While Hash #2 looks like:

files = [{ "file" => "file.txt", "dir" => "/folder/file.txt" }]

Is there a way to loop through hash #2 and create a new hash so the keys are "filename" and "path" instead of "file" and "dir"?

Upvotes: 4

Views: 1045

Answers (2)

Sophistifunk
Sophistifunk

Reputation: 5032

Try this:

files1.concat(files2.map { |old_hash| 
    { 
        "filename" => old_hash["file"], 
        "path" => old_hash["dir"]
    }
})

Upvotes: 0

user229044
user229044

Reputation: 239220

Just replace your key with the new key:

files["path"] = files.delete("dir")

delete returns the value deleted, so you're effectively moving what was at files['dir'] to files['path'].

There is no magic method in Ruby to automate this process for your two arrays; you'd have to loop over the first one, find the value in the second one, and perform the above delete operation:

files1.each do |key,value|
  if old_key = files2.key(value)
    files2[key] = files2.delete(old_key)
  end
end

This has the potential to overwrite values if the keys are already taken in the second array. If you're certain that every value in files1 is also in files2, you can skip the if statement and simply use files2[key] = files2.delete(files2.find(value)) inside the loop.

Upvotes: 7

Related Questions