ruby - Strange behavior of array and hash in nested blocks -


i used inner array (or hash) in nested blocks save data:

p "#1 both inner_arr , outer_arr set empty outside of both loops" outer_arr = [] inner_arr = [] = 0 2.times{   j = 0   2.times{     inner_arr[j] = j+100+i      j += 1   }   p inner_arr   outer_arr[i] = inner_arr   += 1   p outer_arr } p "======================================================" p "#2 outer_arr set empty before both loops while inner_arr set empty inside of outer loop , outside of inner loop" outer_arr_2 = [] = 0 2.times{   j = 0   inner_arr_2 = []   2.times{     inner_arr_2 << j+100+i      j += 1   }   p inner_arr_2   outer_arr_2[i] = inner_arr_2   += 1   p outer_arr_2 } p "======================================================" p "#3 both outer , inner hash set empty outside of both loops" outer_hash_3 = {} inner_hash_3 = {} = 0 2.times{   j = 0   2.times{     inner_hash_3 [j] = j+100+i      j += 1   }   p inner_hash_3   outer_hash_3[i] = inner_hash_3   += 1   p outer_hash_3 } p "======================================================" p "#4 outer_hash set empty before both loops while inner_hash set empty inside of outer loop , outside of inner loop" outer_hash_4 = {} = 0 2.times{   j = 0   inner_hash_4 = {}   2.times{     inner_hash_4[j] = j+100+i      j += 1   }   p inner_hash_4   outer_hash_4[i] = inner_hash_4   += 1   p outer_hash_4 } 

if didn't reset inner array (or hash) when inner array (or hash) changed, updated data had saved in outer array. if reset inner array (or hash), won't update outer array. don't understand why happening. please me understand it.

you've discovered here, guess haven't quite absorbed ramifications of it.

the second form correct way it. because in first case you're recycling same array each iteration, every time insert you're inserting same object on , over.

this best demonstrated here:

a = [ 1 ] b = [ a, ] # => [[1],[1]]  << 2 # => [1,2]  b # => [[1, 2], [1, 2]] 

when insert structure you're not making copy, you're adding technically pointer data. in case b contains 2 pointers same a. modifications made a appear affect every element in b, elements identical definition due way inserted.

if you're aware of this, assigning variables , adding objects structures never results in copy being made, of time works in favour. if need make copy, methods dup or clone help.

re-writing simple test in more ruby fashion not side-steps problem, makes lot simpler:

(0..1).collect |i|   (0..1).collect |j|     j + 100 +   end end 

ruby's enumerable library makes lot of possible. try think of solution problem series of transforms on data.


Comments

Popular posts from this blog

Java 3D LWJGL collision -

spring - SubProtocolWebSocketHandler - No handlers -

methods - python can't use function in submodule -