I have an array of arrays, the ‘inside’ arrays are of different sizes (up to a maximum of 10) (small example, array sizes 7,4,10,2 : [ [“0”,“0”,“0”,“0”,“0”,“0”,“0”],[“2”,“0”,“4”,“0”],[“0”,“0”,“0”,“3”,“0”,“0”,“0”,“4”,“0”,“0”],[“0”,“4”] ] . I need a process or method which can make all elements the same (maximum ) size while retaining the values already there, ie final result is to be sizes 10,10,10,10 : [ [“0”,“0”,“0”,“0”,“0”,“0”,“0”,“0”,“0”,“0”],[“2”,“0”,“4”,“0”,“0”,“0”,“0”,“0”,“0”,“0”],[“0”,“0”,“0”,“3”,“0”,“0”,“0”,“4”,“0”,“0”],[“0”,“4”,“0”,“0”,“0”,“0”,“0”,“0”,“0”,“0”] ]. It seems to me there should be a very simple way to do this, but I just cant find it! Any help would be much appreciated. Thanks in advance!
You can achieve what you need with this by joining an array with the default values and then take the first 10 elements:
def normalize(input)
empty_array = Array.new(10, "0")
input.map {|array| (array + empty_array)[0..9] }
end
input = [ ["0","0","0","0","0","0","0"],["2","0","4","0"],["0","0","0","3","0","0","0","4","0","0"],["0","4"] ]
normalize(input)
By running it, you’ll get the following output:
=> [["0", "0", "0", "0", "0", "0", "0", "0", "0", "0"], ["2", "0", "4", "0", "0", "0", "0", "0", "0", "0"], ["0", "0", "0", "3", "0", "0", "0", "4", "0", "0"], ["0", "4", "0", "0", "0", "0", "0", "0", "0", "0"]]
Thanks jvrc, that’s just what I needed!
1 Like