简体   繁体   中英

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"?

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.

Try this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM