ruby - Fill the array elements with nil -
i have array this:
[[1,2],[2],[3,4,5,6],[7]] i want fill array elements nil. how result:
[[1,2,nil,nil],[2,nil,nil,nil],[3,4,5,6],[7,nil,nil,nil]] i tried:
arr=[[1,2],[2],[3,4,5,6],[7]] l=arr.max_by{|x|x.size}.size arr.map{|x|x+[nil]* (l-x.size)} is there easier way it?
an orthodox way be:
a = [[1,2], [2], [3, 4, 5, 6], [7]] max = a.map(&:length).max - 1 a.each{|a| a[max] ||= nil} # => [[1, 2, nil, nil], [2, nil, nil, nil], [3, 4, 5, 6], [7, nil, nil, nil]] a more interesting way be:
a = [[1,2], [2], [3, 4, 5, 6], [7]] a.max_by(&:length).zip(*a).transpose.drop(1) # => [[1, 2, nil, nil], [2, nil, nil, nil], [3, 4, 5, 6], [7, nil, nil, nil]]
Comments
Post a Comment