给出一系列哈希
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 :(得分: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
答案 2 :(得分: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}