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.
From the fine manual:
string << object → string.
Concatenatesobject
toself
and returnsself
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 }
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.