将多个数组转换为一个数组中的单独哈希值

时间:2013-11-19 10:49:46

标签: ruby arrays merge hash

我需要使用以下数据来构造哈希数组。数组中的第一个元素应该是:

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

给定的数据如下。我真的在努力弄清楚如何做到这一点。一些帮助将非常感激,因为我目前在智慧结束!!!

 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'
 ]

我能想出的唯一解决方案无效。知道为什么???

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)

编辑 - 在你们的帮助下,我得到了解决方案:

 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)

4 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:2)

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

或者如果您不确定每个数组中是否只有五个项目,请将5.times替换为例如salutations.length.times

答案 2 :(得分:0)

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

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

答案 3 :(得分:0)

您必须通过array_index作为参数传递,因为您无法访问方法的 变量。