Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

217
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda