Grouping hashes by value in Ruby and manipulating them

1

I have this array with hashes that I simplified to get smaller. My goal is to join with marca of carros to make a small report showing how much marca is profiting based on compras . Notice that "tag1" repeats 2 times and I do not want this to happen in the report.

carros = [
  {
     modelo: 'modelo1',
     marca: 'marca1',
     compras: [{preco: 20000}, {preco: 30000}]
  },
  {
     modelo: 'modelo2',
     marca: 'marca1',
     compras: [{preco: 45000}, {preco: 60000}]
  },
  {
     modelo: 'modelo3',
     marca: 'marca2',
     compras: [{preco: 77000}, {preco: 23000}]
  }
]

I wanted the final result to be something like:

Marca: marca1
Vendas realizadas: 4
Valor total: 155000
--------
Marca: marca2
Vendas realizadas: 2
Valor total: 100000
    
asked by anonymous 20.01.2016 / 19:08

1 answer

1

One way to do this manipulation is to use each_with_object by initializing with an empty hash. So for each new brand found it initializes a hash for the brand with zeroed counters and adds up the purchases and total value of each car.

carros.each_with_object({}) do |carro, marcas|
  marca, compras = carro.values_at(:marca, :compras)
  marcas[marca] ||= {vendas: 0, valor_total: 0}
  marcas[marca][:vendas] += compras.size
  marcas[marca][:valor_total] += compras.inject(0) { |soma, compra| soma += compra[:preco] }
end

Result:

{
  "marca1" => {
    vendas: 4, 
    valor_total: 155000
  }, 
  "marca2" => {
     vendas: 2, 
     valor_total: 100000
  }
}
    
22.01.2016 / 12:51