2016-02-28 92 views
0

我試圖通過遍歷它將數組轉換爲哈希。我有以下陣列:通過循環將紅寶石數組轉換爲哈希

weekdays = [["Monday",2],["Tuesday",4],["Thursday",5]] 

我循環遍歷數組創建一個哈希像這樣:

hash_weekdays = Hash.new 
weekdays.each do |item| 
    hash_weekdays["weekday"] = item[0] 
    hash_weekdays["number"] = item[1] 
end 

然而,這隻能說明我的最後一個工作日。關於從哪裏出發的任何想法?謝謝!

回答

1

散列保存鍵值對。每個鍵只引用一個值,每個鍵在散列中都是uniq。您的密鑰weekdaynumber的值將在每次迭代時被覆蓋。這就是爲什麼你只能得到最後一次迭代的結果。

您可以將其轉換爲散列數組作爲替代。

weekdays.map{|day, number| {weekday:day, number: number}} 
# => [{:weekday=>"Monday", :number=>2}, {:weekday=>"Tuesday", :number=>4}, {:weekday=>"Thursday", :number=>5}] 

如果你平日或數字是你的主數組中唯一可以使用它們的一種關鍵,而另一個作爲哈希值。

weekdays.to_h 
# => {"Monday"=>2, "Tuesday"=>4, "Thursday"=>5} 

weekdays.to_h.invert 
# => {2=>"Monday", 4=>"Tuesday", 5=>"Thursday"} 
+0

感謝您的解釋@guitarman,是否有AW唉要修改我的'weekdays.each'循環來克服這個問題? – Brandon

+0

謝謝!完美的作品:) – Brandon

1

你可以這樣做,而不是:

weekdays.to_h #=> {"Monday"=>2, "Tuesday"=>4, "Thursday"=>5} 

或修復代碼:

weekdays = [["Monday",2],["Tuesday",4],["Thursday",5]] 

hash_weekdays = Hash.new 
weekdays.each do |item| 
    hash_weekdays[item[0]] = item[1] 
end 

p hash_weekdays #=> {"Monday"=>2, "Tuesday"=>4, "Thursday"=>5} 
1

您需要更改您的代碼如下:

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}