合并两个阵列

时间:2014-02-28 17:11:48

标签: ruby

我有这两个数组

Hotel = 'hilton', 'marriot'
Price = '$350', '$375'

我如何将两个阵列合并在一起,并将价格作为酒店的关键。

所以当我访问

Price[0]

输出

'$350' => 'hilton' (or however the correct output should be)

1 个答案:

答案 0 :(得分:4)

使用Array#zipHash::[]执行以下操作:

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"}

现在选择,无论什么方式适合您的需要。