我有这两个数组
Hotel = 'hilton', 'marriot'
Price = '$350', '$375'
我如何将两个阵列合并在一起,并将价格作为酒店的关键。
所以当我访问
时Price[0]
输出
'$350' => 'hilton' (or however the correct output should be)
答案 0 :(得分:4)
Hotel = 'hilton', 'marriot'
Price = '$350', '$375'
Hash[Price.zip(Hotel)]
# => {"$350"=>"hilton", "$375"=>"marriot"}
但要满足您发布的说明:
Hotel = 'hilton', 'marriot'
Price = '$350', '$375'
array_of_hash = Price.each_index.map { |i| { Price[i] => Hotel[i]} }
# => [{"$350"=>"hilton"}, {"$375"=>"marriot"}]
array_of_hash[0] # => {"$350"=>"hilton"}
现在选择,无论什么方式适合您的需要。