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

220
Visualizações
How to maintain a copy of a hash with original values after changing some of its values in ruby?

I have tried to phrase this to the best of my ability. I have a hash that I perform some operations on but before I do this, I store this hash in another variable. Now when I access this variable, the values seem to have changed, how can I go around it. Example:

hash = {a: "1", b: "2", c: "3"}
hash_copy = hash
hash["a"]=4
puts(hash_copy["a"]) #prints 4 instead of 1

How can I get the put statement to print 1 instead of 4, that is, print the original value.

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

0

deep_dup is your friend hash_copy = hash is just assigning a pointer not making a copy

so ruby specific options are clone and deep_copy In your case copy will do but both should work fine for you

Ruby clone

hash_copy = hash.clone

Rails, a little buggy in earlier rails versions but is a ruby function and will work for you

hash_copy = hash.deep_dup

is what you need

https://apidock.com/rails/Hash/deep_dup

over 4 years ago · Santiago Trujillo Relatório

0

Use Hash#merge instead which returns a modified copy of the hash instead:

hash = {a: "1", b: "2", c: "3"}
hash_copy = hash.merge(a: 4)

In general assigning hash keys should only be done to explicitly modify a hash - for everything else there are better methods.

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