Please tell me how to summarize Ruby two-dimensional arrays.

Asked 2 years ago, Updated 2 years ago, 101 views

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

ruby

2022-09-30 21:35

5 Answers

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>c becomes Proc and is passed as a block.It will prevent you from becoming full of blocks to some extent.


2022-09-30 21:35

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


2022-09-30 21:35

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.


2022-09-30 21:35

 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?


2022-09-30 21:35

 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


2022-09-30 21:35

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.