Search code examples
ruby-on-railsrubyhashkey-value

Ruby : Most efficient way to rename key and value in hash


I have a array of hashes as follows:

"data":[
      {
         "Id":"1",
         "Name":"John"
      },
      {
         "Id":"2",
         "Name":"Robert"
      },
      {
         "Id":"3",
         "Name":"Steve"
      },
      {
         "Name":"Tom",
         "Country":"USA"
      }
   ]

I want to :

  1. Rename all key Name as First_Name.
  2. Then any First_Name value that is Tom to Thomas.

Something like :

"data":[
    {
       "Id":"1",
     "First_Name":"John"
    },
    {
       "Id":"2",
     "First_Name":"Robert"
    },
    {
       "Id":"3",
     "First_Name":"Steve"
    },
    {
       "First_Name":"Thomas",
       "Country":"USA"
    }
 ]

I have gathered something like

data.map{|h| {"First_Name"=>h['Name']} }
data.map{|h| h['First_Name'] = "Thomas" if h['First_Name'] == "Tom" }

What is the most efficient way of doing this ?


Solution

  • I think a better way to edit the data in place is:

    data.each {|h| h["First Name"] = h.delete "Name"}
    data.each {|h| h["First Name"] = "Tom" if h["First Name"] == "Thomas"}
    

    When you call hash.delete it returns the value of the key/value pair it is deleting. So you can grab that in a new key/value pair with the correct key using the = assignment.

    For efficiency just combine it into one loop:

    data.each do |h|
      h["First Name"] = h.delete "Name"
      h["First Name"] = "Tom" if h["First Name"] == "Thomas"
    end