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

205
Vistas
Unexpected returned value from Array#map

I'm getting an unexpected return value with this code:

str = ''; 'abc'.chars.map {|c| str<<c}

Expected output:

["a", "ab", "abc"]

Actual output:

["abc", "abc", "abc"]

Adding a puts(str) for debugging:

str = ''; 'abc'.chars.map {|c| puts(str); str<<c}

a
ab
=> ["abc", "abc", "abc"]

Why is the above code not returning the expected output? Thanks.

over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

From the fine manual:

string << object → string.
Concatenates object to self and returns self

So str << c in the block alters str and then the block itself evaluates to str.

You could say this to get the results you're after:

str = ''
'abc'.chars.map { |c| (str << c).dup }
over 4 years ago · Santiago Trujillo Denunciar

0

It's because each element in your map is returning a reference to str's value, not the actual value of str. So your map is returning 3 references to the value of str and not the value of str at the time of iteration; because each reference to str points to one place in memory at the end that has 'abc', that's why you see the final value of str 3 times.

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