Archive for December 2011

ruby non-intuitive multi-dimensional array assignment

All I want to do is work with an array of arrays…

ruby-1.9.2-p290 :012 > a = Array.new(8,[]) # here lies the problem...
=> [[], [], [], [], [], [], [], []]
ruby-1.9.2-p290 :013 > a[1].push("a")
=> ["a"]
ruby-1.9.2-p290 :014 > a
=> [["a"], ["a"], ["a"], ["a"], ["a"], ["a"], ["a"], ["a"]]

Trying again…

ruby-1.9.2-p290 :019 > a = Array.new(8,Array.new()) # This doesn't solve it
=> [[], [], [], [], [], [], [], []]
ruby-1.9.2-p290 :020 > a[1][0] = 'a'
=> "a"
ruby-1.9.2-p290 :021 > a
=> [["a"], ["a"], ["a"], ["a"], ["a"], ["a"], ["a"], ["a"]]

Argh! Perl makes this so easy…

Ok, the problem was, that the first two ways of initializing the array, were just creating 8 pointers to the SAME array

Now do it the right way:

ruby-1.9.2-p290 :031 > a = Array.new(8) { Array.new(0) } # NOW we have an array of different arrays
=> [[], [], [], [], [], [], [], []]
ruby-1.9.2-p290 :032 > a[1].push('a')
=> ["a"]
ruby-1.9.2-p290 :033 > a
=> [[], ["a"], [], [], [], [], [], []]

Ahh…but I miss an interpreter that always tries to ‘Do The Right Thing’

And, I wish the two versions didn’t look so identical when inspected…