2014-02-28 85 views
1

我有这两个数组合并两个数组一起

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

我怎么会去两个数组合并在一起,使得价格一键酒店。

所以,当我访问

Price[0] 

它输出

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

回答

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

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

+1

正是我在找的东西。 – Seal

+1

'array_of_hash = Price.zip(Hotel).map {| a |哈希[* a]}'摆脱难看的索引。 –

+0

@CarySwoveland太好了, –