【发布时间】:2013-11-19 10:49:46
【问题描述】:
我需要使用以下数据来构造一个哈希数组。数组中的第一个元素应该是:
{
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)
【问题讨论】: