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

209
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 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