Topic: Array of hashes

I need some help to solve this problem:
I have a variable named @data which contains the following

{"phone_number"=>[{"category"=>"home", "phone_number"=>"0621098"}, 
                  {"category"=>"work", "phone_number"=>"06213456"},
                  {"category"=>"mobile", "phone_number"=>"3389876543"}],
"address"=>{"city"=>"Rome", "prov"=>"RM", "zip_code"=>"00192", "street_address"=>"Via Veneto"}}

It contains data related to differend record types (phone numbers, addresses, etc), and for each type it can contain one or more record.

I use the following code to decide if a record has to be saved:

update_contact_methods(@data[:address],"addresses")
update_contact_methods(@data[:phone_number],"phone_numbers")

where

def update_contact_methods(data,model)
  data.each do |d|
    self.send(model).create(d) unless (d.values - [""]).empty?
  end
end


It works correctly only if i have multiple records for the same type; in the example, it works with phone_numbers but not with addresses.
This is due to the fact that phone numbers is an array of hashes, so data.each do |d| does loop over the three phone number hashes.
Having a single address, when data.each do |d| is executed, d is not a hash, but an array containing ["city", "Rome"], and d.values raises an error

undefined method `values' for ["city", "Rome"]:Array

Is there a way to transform the single hash in an array of hashes with only one hash?

Francesco

Re: Array of hashes

No problem, just change your loop to this:

(data.is_a?(Array) ? data : [data]).each do |d|

Hope that does the trick!