Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

204
Views
¿Cómo puedo agrupar contenidos de hash en función de la clave begin_with?

Tengo un hash que actualmente se ve así:

 { "prefix1_key1": [a, b], "prefix1_key2": [c, d], "prefix2_key1": [e, f], "prefix3_key1": [g, h] }

Y me gustaría transferir esto a:

 { "prefix1": [a, b, c, d], "prefix2": [e, f], "prefix3": [g, h] }

¿Hay alguna manera limpia de que pueda hacer esto?

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

Aquí hay una solución de trabajo:

 hash = { "prefix1_key1": [a, b], "prefix1_key2": [c, d], "prefix2_key1": [e, f], "prefix3_key1": [g, h] } hash.each_with_object({}) do |ary, result| key = ary[0].to_s.split('_')[0] (result[key] ||= []).concat(ary[1]) end
over 4 years ago · Santiago Trujillo Report

0

Aporte

 hash = { "prefix1_key1": ['a', 'b'], "prefix1_key2": ['c', 'd'], "prefix2_key1": ['e', 'f'], "prefix3_key1": ['g', 'h'] }

Código

 p hash.group_by { |k, v| k.to_s.split("_").first } .transform_values { |x| x.flat_map(&:pop) }

Producción

 {"prefix1"=>["a", "b", "c", "d"], "prefix2"=>["e", "f"], "prefix3"=>["g", "h"]}
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!