2016-11-13 54 views
1

我想轉換:替代使用相同的密鑰轉換一個數組的哈希和值

[:one, :two, :three] 

到:

{one: :one, two: :two, three: three} 

到目前爲止,我使用的是這樣的:

Hash[[:basic, :silver, :gold, :platinum].map { |e| [e, e] }] 

但我想知道是否有可能通過其他方式?

這是在Rails enum定義模型中使用,將值保存爲數據庫中的字符串。

回答

1

我承認掛機:選擇的話,我寧願構建哈希從頭開始而不是創建一個數組和合作夥伴顛覆它到哈希。

[:one, :two, :three].each_with_object({}) { |e,h| h[e]=e } 
    #=> {:one=>:one, :two=>:two, :three=>:three} 
+0

與從頭開始創建哈希完全同意一樣,我通常採取'在這樣的情況下each_with_object',但'a.zip(一).to_h'這麼多少打字:D –

6

Array#zip

a = [:one, :two, :three] 
a.zip(a).to_h 
#=> {:one=>:one, :two=>:two, :three=>:three} 

Array#transpose

[a, a].transpose.to_h 
#=> {:one=>:one, :two=>:two, :three=>:three} 
1

這裏是另一種方式與map

>> [:one, :two, :three].map { |x| [x,x] }.to_h 
=> {:one=>:one, :two=>:two, :three=>:three} 
+0

這是什麼OP已經:) –

相關問題