Make 2 arrays of the same size

2 arrays of arrays:

a = [[1, 2], [22, 11], [18, 9]] b = [[1, 81]] 

What is the best way to populate the second with [0,0] so they are the same size?

+5
source share
5 answers
 b.fill(b.size..a.size - 1) { [0, 0] } 
+5
source

In my opinion, this is more readable:

 (a.length - b.length).times do b << [0, 0] end 
+4
source

Not the most efficient, but pretty readable:

 b << [0,0] until a.size == b.size 

A bit more efficient:

 b.concat [[0,0]] * (a.size-b.size) 
+4
source

I like fill , but that seems to have been accepted. Here you can return the desired array without mutation b . This was not requested, but it may be useful in some applications:

 Array.new(a.size) { |i| b[i] || [0,0] } #=> [[1, 81], [0, 0], [0, 0]] 

You could, of course, put b = in front.

Another way in place:

 b.concat [[0,0]]*(a.size-b.size) 

Hey, this is fun. Another (assuming elements b are nil ):

 a.each_index { |i| b[i] ||= [0,0] } b 
+2
source

I would append while size is smaller because I think it reads well:

 a = [[1, 2], [22, 11], [18, 9]] b = [[1, 81]] b << [0, 0] while b.size < a.size b #=> [[1, 2], [0, 0], [0, 0]] 
+1
source

All Articles