Home > Software design >  Adding more keys to a list of hash conditionally
Adding more keys to a list of hash conditionally

Time:09-29

Hello I have a question similar to this (Add a key value pair to all hashes in an array of hashes) but with a bit more complexity

def location_records(options)
  materials = [
    {
      name: 'object1'
      area: 'USA'
    },
    {
      name: 'object2'
      area: 'USA'
    }
  ]

  materials.map!{ |material| record_additional_info(material, options) if %w[USA].include?(options.extra_fields_required) }
end

def record_additional_info(materials, options)
  materials[:zip] = 63123
  materials[:state] = 'Missouri'
  materials[:city] = 'Kansas City'
end

Say I have this - and I have an array of hash [{name: 'object1', area: 'USA'}, {name: 'object2', area: 'USA'}]

I want to selective only add additional keys to the hash ONLY if the extra_fields_required is contained in the list of String I provided, say only USA.

So the output of this should be [{name: 'object1', area: 'USA', zip: 63123, state: 'Missouri', city: 'Kansas City'}, {name: 'object2', area: 'USA', zip: 63123, state: 'Missouri', city: 'Kansas City'}]

But for some reason, I keep getting -

NoMethodError: undefined method `each' for "Kansas City":String

CodePudding user response:

You should return the material hash from an invoked method

def location_records(options)
  materials = [
    {
      name: 'object1',
      area: 'USA'
    },
    {
      name: 'object2',
      area: 'USA'
    }
  ]

  materials.map!{ |material| record_additional_info(material) if %w[USA].include?(options.extra_fields_required) }

  puts materials     # Prints modified array of hashes
end

def record_additional_info(material)
  material[:zip] = 63123
  material[:state] = 'Missouri'
  material[:city] = 'Kansas City'

  material     # Return the hash object
end

Output:

{:name=>"object1", :area=>"USA", :zip=>63123, :state=>"Missouri", :city=>"Kansas City"}
{:name=>"object2", :area=>"USA", :zip=>63123, :state=>"Missouri", :city=>"Kansas City"}
  • Related