How do I organize a two-dimensional array with a person name in the array [0]
and a score in the array [1]
?
score=[["taro", 10],["taro", 70],["taro", 170],["jiro", 90],["jiro", 55]]
Desired Output
taro=>250
jiro=>145
It's not good to show too many patterns because it's going to be a great joy or a code golf tournament, but I didn't have an example of my favorite code, so I'm going to participate.
score.group_by(&:first).transform_values{|a|a.sum(&:last)}
Note that Hash#transform_value
and Array#sum
start from 2.4.0, &first>
is the expression
&first>
becomes c
Proc
and is passed as a block.It will prevent you from becoming full of blocks to some extent.
score.group_by {|name,_|name}
.map do | name, entries |
[ name, entries.map { | _ , value | value }.sum ]
end.to_h
The Enumerable class can be accomplished using group_by
, sum
, map
, to_h
.
https://docs.ruby-lang.org/ja/latest/class/Enumerable.html
I made it by licking the array and putting each key into the hash.
score_map=Hash.new()
score.each {|pair|
score_map.has_key?(pair[0])?score_map[pair[0]]+=pair[1]:score_map[pair[0]]=pair[1]
}
# = > {"taro" = > 250, "jiro" = > 145}
There may be a smarter way.
score=[["taro", 10],["taro", 70],["taro", 170],["jiro", 90],["jiro", 55]]
result=score.group_by do|s|
s[0]
end.map do |k,v |
{ k = > v.sum { | num | num[1]}
end
puts result
#=>[{"taro"=>250}, {"jiro"=>145}]
Like this?
score=[["taro", 10],["taro", 70],["taro", 170],["jiro", 90],["jiro", 55]]
hash = {}
score.each do|a|
if hash[a[0]]
hash[a[0]]=hash[a[0]]+a[1]
else
hash[a[0]]=a[1]
end
end
pp hash
© 2024 OneMinuteCode. All rights reserved.