Brad,
這裏有兩種方法可以產生散列。我將使用以下作爲一個例子:
class ContestStanding
def checkit
puts "hi"
end
end
my_keys = [1,2,3]
使用Enumerable#each_with_object
h = my_keys.each_with_object({}) { |k,h| h[k] = ContestStanding.new }
#=> {1=>#<ContestStanding:0x000001010efdd8>,
# 2=>#<ContestStanding:0x000001010efdb0>,
# 3=>#<ContestStanding:0x000001010efd88>}
h[1].checkit #=> "hi"
each_with_object
創建和由所述塊參數h
引用空數組。第一值傳遞到塊(和分配給該塊參數k
)是my_keys.first => 1
,所以具有
h[1] = ContestStanding.new
被類似地產生的散列值的其它元件。
使用Array.zip
Hash[my_keys.zip(Array.new(my_keys.size) {ContestStanding.new})]
#=> {1=>#<ContestStanding:0x0000010280f720>,
# 2=>#<ContestStanding:0x0000010280f6f8>,
# 3=>#<ContestStanding:0x0000010280f6d0>}
,或者爲Ruby V2。0+
my_keys.zip(Array.new(my_keys.size) {ContestStanding.new}).to_h
#=> {1=>#<ContestStanding:0x0000010184bd48>,
# 2=>#<ContestStanding:0x0000010184bd20>,
# 3=>#<ContestStanding:0x0000010184bcf8>}
這裏執行以下步驟:
a = Array.new(my_keys.size) {ContestStanding.new}
#=> [#<ContestStanding:0x0000010185b248>,
# #<ContestStanding:0x0000010185b220>,
# #<ContestStanding:0x0000010185b1f8>]
b = my_keys.zip(a)
#=> [[1, #<ContestStanding:0x0000010185b248>],
# [2, #<ContestStanding:0x0000010185b220>],
# [3, #<ContestStanding:0x0000010185b1f8>]]
b.to_h
#=> {1=>#<ContestStanding:0x0000010185b248>,
# 2=>#<ContestStanding:0x0000010185b220>,
# 3=>#<ContestStanding:0x0000010185b1f8>}
您的解決方案
我發現你的解決方案感興趣。這是解釋一個一個方式,它是如何工作的:
enum = Enumerator.new { |y| loop { y << ContestStanding.new } }
#=> #<Enumerator: #<Enumerator::Generator:0x000001011a9530>:each>
a1 = my_keys.size.times.with_object([]) { |k,a| a << enum.next }
#=> [#<ContestStanding:0x000001018820a0>,
# #<ContestStanding:0x00000101882028>,
# #<ContestStanding:0x00000101881fb0>
a2 = my_keys.zip(a1)
#=> [[1, #<ContestStanding:0x000001018820a0>],
# [2, #<ContestStanding:0x00000101882028>],
# [3, #<ContestStanding:0x00000101881fb0>]]
Hash[a2]
#=> {1=>#<ContestStanding:0x000001018820a0>,
# 2=>#<ContestStanding:0x00000101882028>,
# 3=>#<ContestStanding:0x00000101881fb0>}
布拉德,你可以使用 'my_keys.each_with_object({}){| K,H | h [k] = ContestStanding.new}'其中'my_keys.each_with_object({})'是一個枚舉器。要使用'zip':'Hash [my_keys.zip(Array.new(my_keys.size,Hash.new {| h,k | h [k] = ContestStanding.new}))]'。這是你尋找的那種東西嗎? –
爲了記錄,@ CarySwoveland的方法是我會使用的方法,我對你如何解決問題印象更深刻,我從來沒有想過(有點驚訝它的作品)!另一種方法肯定比較習慣,不太混亂。 –
@CarySwoveland查看我對幾個問題的編輯 –