Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

206
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!