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:
deletereturns the value deleted, so you’re effectively moving what was atfiles['dir']tofiles['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
deleteoperation: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
files1is also infiles2, you can skip the if statement and simply usefiles2[key] = files2.delete(files2.find(value))inside the loop.