Group hashes by Ruby value and manipulate them

Asked

Viewed 515 times

1

I have this hashed array that I’ve simplified to get smaller. My goal is to join by marca of carros to make a small report showing how much that marca is making a profit based on compras. Notice that "mark 1" repeats twice and I don’t want that 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 end result to be something like:

Marca: marca1
Vendas realizadas: 4
Valor total: 155000
--------
Marca: marca2
Vendas realizadas: 2
Valor total: 100000

1 answer

1


One way to do this manipulation is by using each_with_object Initiating with an empty hash. Then for each new brand found initializes a hash for the brand with zero counters and sums 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

Upshot:

{
  "marca1" => {
    vendas: 4, 
    valor_total: 155000
  }, 
  "marca2" => {
     vendas: 2, 
     valor_total: 100000
  }
}
  • I was able to adapt to my problem, thank you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.