The biggest problem here is that you're not creating a two dimensional array like you think you are, but instead you're creating two arrays. This is because you're passing in a singular array as a default, not a block that can generate them.
What you were expecting was this:
array1 = [ array21, array22, array23, array24 ]
What you were actually getting is this:
array1 = [ array2, array2, array2, array2 ]
This is easily fixed by converting the last argument to a block:
def fun(str)
maxlength = Array.new(str.length) { Array.new(str.length,0) }
str.chars.collect(&:to_i).each_with_index do |v,i|
maxlength[i][i] = v
end
print maxlength
end
print fun("1234")
I've also switched to using chars which splits up the string as you want.
So the problem was that you were setting the positions correctly, but as all the second level arrays were the same array, you didn't get the result you were expecting.
Update: Added each_with_index from Chris's answer which makes this work with arbitrary numbers.