2016-05-10 51 views
0

鑑於哈希基於一些關鍵

arr = [{'city' => 'Bangalore','device' => 'desktop','users' => '20'}, 
     {'city' => 'Bangalore','device' => 'tablet','users' => '20'}, 
     {'city' => 'Bangalore','device' => 'mobile','users' => '20'}, 
     {'city' => 'Pune','device' => 'desktop','users' => '20'}, 
     {'city' => 'Pune','device' => 'tablet','users' => '20'}, 
     {'city' => 'Pune','device' => 'mobile','users' => '20'}, 
     {'city' => 'Mumbai','device' => 'desktop','users' => '20'}, 
     {'city' => 'Mumbai','device' => 'tablet','users' => '20'}, 
     {'city' => 'Mumbai','device' => 'mobile','users' => '20'}]  

我怎麼能生產出哈希以下數組的數組的值如何聚合紅寶石哈希?

[{'city' => 'Bangalore', 'users' => '60'}, 
{'city' => 'Pune', 'users' => '60'}, 
{'city' => 'Mumbai','users' => '60'}] 
+0

是此活動記錄的對象? – uzaif

+0

你有試過什麼嗎? –

+0

這不是主動記錄,我用過每個循環並建立了一個新對象,但我想知道更好的方法 – Neevany

回答

0

不喜歡它:

hash = [{'city' => 'Bangalore','device' => 'desktop','users' => '20'}, {'city' => 'Bangalore','device' => 'tablet','users' => '20'}, {'city' => 'Bangalore','device' => 'mobile','users' => '20'}, {'city' => 'Pune','device' => 'desktop','users' => '20'}, 
{'city' => 'Pune','device' => 'tablet','users' => '20'}, {'city' => 'Pune','device' => 'mobile','users' => '20'}, {'city' => 'Mumbai','device' => 'desktop','users' => '20'}, 
{'city' => 'Pune','device' => 'tablet','users' => '20'}, {'city' => 'Mumbai','device' => 'mobile','users' => '20'}] 

new_hash = hash.map{|obj| {:city => obj[:city], :users => obj[:users]}} 
+1

「散列」可能不是陣列的最佳名稱。 –

0

試試這個

def setter hash, hash_array_new 
    new_hash = {} 
    new_hash["users"] = hash["users"].to_i 
    new_hash["city"] = hash["city"] 
    hash_array_new << new_hash 
end 

hash_array_new = [] 
hash_array.each do |hash| 
    count = 0 
    hash_array_new.each do |new_hash| 
    if hash["city"] == new_hash["city"] 
     new_hash["users"] += hash["users"].to_i 
     count = count+1 
    end 
    end 
    if count == 0 
    setter hash, hash_array_new 
    end 
    if hash_array_new.blank? 
    setter hash, hash_array_new 
    end 
end 


puts hash_array_new //display resultant array 
0
arr.each_with_object(Hash.new(0)) { |g,h| h[g["city"]] += g["users"].to_i }. 
    map { |city,users| { 'city' => city, 'users' => users.to_s } } 
    #=> [{"city"=>"Bangalore", "users"=>"60"}, 
    # {"city"=>"Pune", "users"=>"60"}, 
    # {"city"=>"Mumbai", "users"=>"60"}] 

Hash.new(0)有時也被稱爲計數哈希值。零是默認值。 (參見Hash::new)。這意味着對於

h[g["city"]] += g["users"].to_i 

它將擴展爲

h[g["city"]] = h[g["city"]] + g["users"].to_i 

h[g["city"]]右側被替換的默認值爲零時h不具有關鍵g["city"]

注意

arr.each_with_object(Hash.new(0)) { |g,h| h[g["city"]] += g["users"].to_i } 
    #=> {"Bangalore"=>60, "Pune"=>60, "Mumbai"=>60}