Ruby根据一个散列值将散列组合到一个数组中 [英] Ruby combining hashes in an array based on one hash value

查看:124
本文介绍了Ruby根据一个散列值将散列组合到一个数组中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  [
{id=> 1 ,name=>蝙蝠侠,net_worth=> 100,vehicles=> 2},
{id= 1, ,net_worth=> 100,车辆=> 2},
{id= 2,name=>超人,net_worth=>车辆=> 2},
{id=> 3,name=>Wonderwoman,net_worth=> 100,vehicles=> 2} b]

我想在保留它的同时基于id值组合散列,保留名称,并将net_worth和车辆值相加。

所以最终的数组将如下所示:

  [
{id=> 1,name=>蝙蝠侠,net_worth=> 200,车辆=> 4},
id = 2name=>超人,net_worth=> 100,vehicles=> 2},
{id= 3, name=>Wonderwoman,net_worth=> 100,vehicles=> 2}
]


解决方案

这里是解决方案你的问题的离子。正如你所看到的,你应该通过id和name对行进行分组,然后计算其他值的总和并生成结果:

  rows = [ 
{id=> 1,name=>蝙蝠侠,net_worth=> 100,vehicles=> 2},
{id=> ; 1,name=>蝙蝠侠,net_worth=> 100,vehicles=> 2},
{id=> 2,name=>超人,net_worth=> 100,车辆=> 2},
{id= 3,name=>Wonderwoman,net_worth=> 100 ,车辆=> 2}
]

groups = rows.group_by {| row | [row ['id'],row ['name']]}

result = groups.map do | key,values |
id,name = * key

total_net_worth = values.reduce(0){| sum,value | sum + value ['net_worth']}
total_vehicles = values.reduce(0){| sum,value | sum + value ['vehicles']}

{id=> id,name=>名称,net_worth=> total_net_worth,车辆=> total_vehicles}
结束

结果


I have an array of hashes that looks like:

[
  {"id"=>1, "name"=>"Batman", "net_worth"=>100, "vehicles"=>2},
  {"id"=>1, "name"=>"Batman", "net_worth"=>100, "vehicles"=>2},
  {"id"=>2, "name"=>"Superman", "net_worth"=>100, "vehicles"=>2},
  {"id"=>3, "name"=>"Wonderwoman", "net_worth"=>100, "vehicles"=>2}
]

I'd like to combine hashes based on the id value while preserving it, preserve the name, and sum the net_worth and vehicles values.

So the final array would look like:

[
  {"id"=>1, "name"=>"Batman", "net_worth"=>200, "vehicles"=>4},
  {"id"=>2, "name"=>"Superman", "net_worth"=>100, "vehicles"=>2},
  {"id"=>3, "name"=>"Wonderwoman", "net_worth"=>100, "vehicles"=>2}
]

解决方案

Here is solution of your problem. As you can see you should group rows by id and name, then calculate sum of other values and build result:

rows = [
    {"id"=>1, "name"=>"Batman", "net_worth"=>100, "vehicles"=>2},
    {"id"=>1, "name"=>"Batman", "net_worth"=>100, "vehicles"=>2},
    {"id"=>2, "name"=>"Superman", "net_worth"=>100, "vehicles"=>2},
    {"id"=>3, "name"=>"Wonderwoman", "net_worth"=>100, "vehicles"=>2}
]

groups = rows.group_by {|row| [row['id'], row['name']] }

result = groups.map do |key, values|
  id, name = *key

  total_net_worth = values.reduce(0) {|sum, value| sum + value['net_worth'] }
  total_vehicles = values.reduce(0) {|sum, value| sum + value['vehicles'] }

  { "id" => id, "name" => name, "net_worth" => total_net_worth, "vehicles" => total_vehicles }
end

p result

这篇关于Ruby根据一个散列值将散列组合到一个数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆