John
John

Reputation: 443

Converting several array into separate hashes within one array

I need to use the following data to construct an array of hashes. The first element in the array should be:

 {
   salutation: 'Mr.'
   first_name: 'John',
   last_name: 'Dillinger',
   address: '33 Foolish Lane, Boston MA 02210'
 }

The given data is below. I am really struggling to figure out how to do this. Some help would be greatly appreciated as I am currently at wits end!!!

 salutations = [
   'Mr.',
   'Mrs.',
   'Mr.',
   'Dr.',
   'Ms.'
 ]

 first_names = [
   'John',
   'Jane',
   'Sam',
   'Louise',
   'Kyle'
 ]

 last_names = [
   'Dillinger',
   'Cook',
   'Livingston',
   'Levinger',
   'Merlotte'
 ]

 addresses = [
   '33 Foolish Lane, Boston MA 02210',
   '45 Cottage Way, Dartmouth, MA 02342',
   "54 Sally's Court, Bridgewater, MA 02324",
   '4534 Broadway, Boston, MA 02110',
   '4231 Cynthia Drive, Raynham, MA 02767'
 ]

The only solution i was able to come up with doesn't work. Any idea why???

array_of_hashes = []
array_index = 0

 def array_to_hash (salutations, first_names, last_names, addresses)
   while array_index <= 5
     hash = {}
     hash[salutation] = salutations(array_index)
     hash[first_name] = first_names(array_index)
     hash[last_name] = last_names(array_index)
     hash[address] = addresses(array_index)
     array_of_hashes << hash
     array_index += 1
  end
end

array_to_hash(salutations,first_names,last_names,addresses)

EDIT - With help from you guys I was able to get my solution to work:

 def array_to_hash (salutations, first_names, last_names, addresses)
   array_of_hashes = []
   array_index = 0
   while array_index <= 4
     hash = {}
     hash[:salutation] = salutations[array_index]
     hash[:first_name] = first_names[array_index]
     hash[:last_name] = last_names[array_index]
     hash[:address] = addresses[array_index]
     array_of_hashes << hash
     array_index += 1
   end
   puts array_of_hashes
 end

 array_to_hash(salutations,first_names,last_names,addresses)

Upvotes: 0

Views: 55

Answers (4)

ooransoy
ooransoy

Reputation: 797

You have to pass you have to pass array_index in as a parameter because you can't access variables outside of the method.

Upvotes: 0

Zippie
Zippie

Reputation: 6088

5.times.map do |x|
  {    
   salutation: salutations[x],
   first_name: first_names[x],
   last_name: last_names[x],
   address: addresses[x]
  }
end

or if you're not sure if it's going to be only five items in each array, substitute 5.times with e.g. salutations.length.times.

Upvotes: 2

hirolau
hirolau

Reputation: 13901

keys = [:salutations, :first_names, :last_names, :addresses]
data = [ salutations,  first_names,  last_names,  addresses].transpose

data.map!{|person|  Hash[keys.zip(person)]}

Upvotes: 0

sawa
sawa

Reputation: 168101

[salutations, first_names, last_names, addresses].transpose
.map{|a| Hash[%i[salutation first_name last_name address].zip(a)]}

Upvotes: 3

Related Questions