Project

General

Profile

Bug #14107

Updated by nobu (Nobuyoshi Nakada) over 6 years ago

Hi. I was working with `each_with_object` and found a bug. 
 I was needed to iterate through the array and have an memo object at the same time so I've tried to use next code: 

 Here is an array: 

 ~~~ruby ~~~ 
 d = [1, 2, 3, 4, 5, 6, 7] 
 ~~~ 

 And what I've tried to do: 

 ~~~ruby ~~~ 
 d.each_with_object([1, {}]) do |item, (index, chunks)| 
   index +=1 if item % 3 == 0 

   chunks[index] ||= [] 
   chunks[index].push(item) 

   
  
   memo = [index, chunks] 
 end 
 ~~~ 

 Second variation is: 

 ~~~ruby ~~~ 
 d.each_with_object([1, {}]) do |item, memo| 
   index, chunks = memo 
   index +=1 if item % 3 == 0 

   chunks[index] ||= [] 
   chunks[index].push(item) 

   
  
   [index, chunks] 
 end 
 ~~~ 

 Or even if I mutate memo directly at the end like: 

 ~~~ruby ~~~ 
 d.each_with_object([1, {}]) do |item, memo| 
   index, chunks = memo 
   index +=1 if item % 3 == 0 

   chunks[index] ||= [] 
   chunks[index].push(item) 

   
  
   memo = [index, chunks] 
 end 
 ~~~ 

 It always returns: 

 ```ruby ``` 
 [1, { 1 => [1, 2, 4, 5, 7], 2 => [3, 6] }] 
 ``` 

 For some reason It's mutate an Hash inside the array but not mutate an Integer. 


 I was expecting that index will increase each time and I'll get: 


 ```ruby ``` 
 [3, { 1 => [1, 2], 2 => [3, 4, 5], 3 => [6, 7] }] 
 ``` 

 Ruby -v: 

 ruby 2.4.0p0 (2016-12-24 revision 57164) [x86_64-linux] 
 ruby 2.3.1p112 (2016-04-26 revision 54768) [x86_64-linux]

Back