您需要更改您的代碼如下:
hash_weekdays = Hash.new
weekdays.each do |item|
hash_weekdays[item[0]] = item[1]
end
hash_weekdays
#=> {"Monday"=>2, "Tuesday"=>4, "Thursday"=>5}
當weekdays
(["Monday",2]
)第一元件被傳遞到塊,塊變量被分配它的值:
item = ["Monday",2]
由於需要引用的item
每個元素,這是常見的是使用兩種嵌段變量,其值使用並行分配被分配(又名多重分配):
day, nbr = ["Monday",2]
#=> ["Monday", 2]
day #=> "Monday"
nbr #=> 2
這允許你寫
hash_weekdays = {} # the more common way of writing hash_weekdays = Hash.new
weekdays.each { |day, nbr| hash_weekdays[day] = nbr } # used {...} rather than do..end
hash_weekdays
這無疑更加清晰。
注意,首先初始化hash_weekdays
到一個空的散列,那麼就需要在端線hash_weekdays
如果希望獲得的散列的新值(作爲方法的最後一行,例如)。可以通過使用該方法Enumerable#each_with_object這減少到一行(非常紅寶石樣):
weekdays.each_with_object({}) { |item, hash_weekdays| hash_weekdays[item[0]] = item[1] }
#=> {"Monday"=>2, "Tuesday"=>4, "Thursday"=>5}
聲明本使用並行分配。傳遞到塊,[["Monday", 2], {}]
第一元件,被分配如下:
item, hash_weekdays = weekdays.each_with_object({}).next
#=> [["Monday", 2], {}]
item
#=> ["Monday", 2]
hash_weekdays
#=> {}
紅寶石方式是在稍微更復雜的方式來使用並行賦值:
weekdays.each_with_object({}) { |(day, nbr), hash_weekdays|
hash_weekdays[day] = nbr }
#=> {"Monday"=>2, "Tuesday"=>4, "Thursday"=>5}
正如其他人指出的那樣,最直接的答案是使用方法Hash::[]或(在V2.0中引入)Array#to_h:
Hash[weekdays]
#=> {"Monday"=>2, "Tuesday"=>4, "Thursday"=>5}
Hash[*weekdays.flatten] #=> Hash["Monday", 2, "Tuesday", 4, "Thursday", 5]
#=> {"Monday"=>2, "Tuesday"=>4, "Thursday"=>5}
weekdays.to_h
#=> {"Monday"=>2, "Tuesday"=>4, "Thursday"=>5}
感謝您的解釋@guitarman,是否有AW唉要修改我的'weekdays.each'循環來克服這個問題? – Brandon
謝謝!完美的作品:) – Brandon