Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

536
Visualizações
Split text in hash value into new hash using separator in Ruby

I found another question similar to the one I have, but I was not able to replicate it (probably because it doesn't deal with hashes neither have symbols).

So, given the following array of hashes:

[{:id=>1, :name=>"AA;AB;AC", :title=>"A row"},
 {:id=>2, :name=>"BA;BB", :title=>"B row"},
 {:id=>3, :name=>"CA", :title=>"C row"}]

I would like to achieve the following result:

[{:id=>1, :name=>"AA", :title=>"A row"},
 {:id=>1, :name=>"AB", :title=>"A row"},
 {:id=>1, :name=>"AC", :title=>"A row"},
 {:id=>2, :name=>"BA", :title=>"B row"},
 {:id=>2, :name=>"BB", :title=>"B row"},
 {:id=>3, :name=>"CA", :title=>"C row"}]

In brief, I want to fully replicate a hash, splitting it by semicolon. In this case, :name have two hashes with one or more semicolons that should be split and consist on another hash.

I hope you have understand my question. Any help is highly appreciated.

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

You could iterate over your array of hashes and split their name value, and map that result merging it with the current hash. Then you can flatten the result:

[
  {:id=>1, :name=>"AA;AB;AC", :title=>"A row"},
  {:id=>2, :name=>"BA;BB", :title=>"B row"},
  {:id=>3, :name=>"CA", :title=>"C row"}
].flat_map do |hsh|
  hsh[:name].split(";").map do |name|
    hsh.merge(name: name)
  end
end

# [{:id=>1, :name=>"AA", :title=>"A row"},
#  {:id=>1, :name=>"AB", :title=>"A row"},
#  {:id=>1, :name=>"AC", :title=>"A row"},
#  {:id=>2, :name=>"BA", :title=>"B row"},
#  {:id=>2, :name=>"BB", :title=>"B row"},
#  {:id=>3, :name=>"CA", :title=>"C row"}]
over 4 years ago · Santiago Trujillo Relatório

0

Using Enumerable#each_with_object

ary =
  [
    { id: 1, name: "AA;AB;AC", title: "A row" },
    { id: 2, name: "BA;BB", title: "B row" },
    { id: 3, name: "CA", title: "C row" }
  ]

ary.each_with_object([]) do |hash, new_ary|
  hash[:name].split(";").each do |name|
    new_ary << hash.merge(name: name)
  end
end
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda