2014-09-27 33 views

回答

1

您可以使用Hash::[]

Hash[(1959..1962).map { |x| [x, 0] }] 
# => {1959=>0, 1960=>0, 1961=>0, 1962=>0} 

Enumerable#to_h在Ruby中2.1+:

(1959..1962).map { |x| [x, 0] }.to_h 
# => {1959=>0, 1960=>0, 1961=>0, 1962=>0} 

(改結束一年的產出簡潔)

1

您可以使用inject與數組來形成哈希,如下所示:

(1959..2014).inject({}) { |hash, year| hash[year] = 0; hash } 

inject就像每個運行在枚舉的每個成員上一樣,但它將2個參數傳遞給塊,當前對象和可用於收集結果的對象,在本例中爲散列。

或者,如@sawa在下面的評論中指出:

(1959..2014).each_with_object({}) { |year, hash| hash[year] = 0 } 

each_with_object不要求你在塊的像inject做最後返回的對象。使用簡單範圍,而不是數組。增加了each_with_object選項。

+0

您不需要將範圍轉換爲數組。這是額外的步驟,是浪費。而'each_with_object'在這裏會更好。 – sawa 2014-09-27 14:40:08

+0

謝謝,添加了'each_with_object'選項。沒有意識到它比'inject'更有用。 – philnash 2014-09-27 15:01:17

1

方式一:

Hash[[*1959..2014].product([0])] 
+0

或者在Ruby 2.1中,'[* 1959..2014] .product([0])。to_h' – 2014-09-28 01:00:41