Home > Software design >  Ruby : Most efficient way to rename key and value in hash
Ruby : Most efficient way to rename key and value in hash

Time:01-13

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 ?

CodePudding user response:

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

CodePudding user response:

If you are using Ruby 3.0 , you could do something like:

data.each do |hash|
  hash.transform_keys!({Name: 'First_Name'})
  hash.transform_values! { |v| v == 'Tom' ? 'Thomas' : v }
end

If you are using Ruby versions below 3.0, then you could:

data.each do |hash|
  hash.transform_keys! { |k| k == 'Name' ? 'First_Name' : k }
  hash.transform_values! { |v| v == 'Tom' ? 'Thomas' : v }
end
  • Related