简体   繁体   中英

Add values of an array inside a hash

I created a hash that has an array as a value.

{
  "0":[0,14,0,14],
  "1":[0,14],
  "2":[0,11,0,12],
  "3":[0,11,0,12],
  "4":[0,10,0,13,0,11],
  "5":[0,10,0,14,0,0,0,11,12,0],
  "6":[0,0,12],
  "7":[],
  "8":[0,14,0,12],
  "9":[0,14,0,0,11,14],
  "10":[0,11,0,12],
  "11":[0,13,0,14]
}

I want the sum of all values in each array. I expect to have such output as:

{
  "0":[24],
  "1":[14],
  "2":[23],
  "3":[23],
  "4":[34],
  "5":[47],
  "6":[12],
  "7":[],
  "8":[26],
  "9":[39],
  "10":[23],
  "11":[27]
}

I do not know how to proceed from here. Any pointers are thankful.

I would do something like this:

hash = { "0" => [0,14,0,14], "1" => [0,14], "7" => [] }

hash.each { |k, v| hash[k] = Array(v.reduce(:+)) }
# => { "0" => [28], "1" => [14], "7" => [] }

For hash object you as this one.

hash = {"0"=>[0,14,0,14],"1"=>[0,14],"2"=>[0,11,0,12],"3"=>[0,11,0,12],"4"=>[0,10,0,13,0,11],"5"=>[0,10,0,14,0,0,0,11,12,0],"6"=>[0,0,12],"7"=>[],"8"=>[0,14,0,12],"9"=>[0,14,0,0,11,14],"10"=>[0,11,0,12],"11"=>[0,13,0,14]}

You could change value of each k => v pair

hash.each_pair do |k, v|
  hash[k] = [v.reduce(0, :+)]
end

will resolve in

hash = {"0"=>[28], "1"=>[14], "2"=>[23], "3"=>[23], "4"=>[34], "5"=>[47], "6"=>[12], "7"=>[0], "8"=>[26], "9"=>[39], "10"=>[23], "11"=>[27]} 

Classic example for map/reduce. You need to iterate on the hash keys and values ( map {|k,v|} ), and for each value count the sum using reduce(0) {|acc, x| acc+x} reduce(0) {|acc, x| acc+x}

h = {1 => [1,2,3], 2 => [3,4,5], 7 => []} #example
a = h.map {|k,v| [k ,v.reduce(0) {|acc, x| acc+x}] }
=> [[1, 6], [2, 12], [7, 0]]
Hash[a]
=> {1=>6, 2=>12, 7=>0}

If your string is just like you mentioned you can parse it using JSON, or jump that step if you have already an Hash. You can check the documentation of inject here

require 'json'
json_string =  '
{
  "0":[0,14,0,14],
  "1":[0,14],
  "2":[0,11,0,12],
  "3":[0,11,0,12],
  "4":[0,10,0,13,0,11],
  "5":[0,10,0,14,0,0,0,11,12,0],
  "6":[0,0,12],
  "7":[],
  "8":[0,14,0,12],
  "9":[0,14,0,0,11,14],
  "10":[0,11,0,12],
  "11":[0,13,0,14]
}
'
hash = JSON.parse json_string

result = Hash.new

hash.each do |key, value|

  result[key] = value.inject(:+)

end

puts result.inspect

and the result:

{"0"=>28, "1"=>14, "2"=>23, "3"=>23, "4"=>34, "5"=>47, "6"=>12, "7"=>nil, "8"=>26, "9"=>39, "10"=>23, "11"=>27}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM