1 2 class Array 3 def pad!(expected_length, pad_item = nil) 4 while expected_length > length 5 self << pad_item 6 end 7 self 8 end 9 end
1 2 class Array 3 def pad!(expected_length, pad_item = nil) 4 expected_length.times { self << pad_item } 5 self 6 end 7 end
But there's not much point, because there IS actually a padding method for Ruby arrays. Therefore, you can simply do:
1 2 x = [1, 2, 3] 3 4 # Instead of x.pad!('pad', 4) 5 x.fill 'pad', x.length, 4
1 x = [1,2,3] 2 # Padding to 10 elements total: 3 x[9] ||= nil 4 #=> [1, 2, 3, nil, nil, nil, nil, nil, nil, nil]
That will modify the array in place, of course. You can use dup to get around that if you want.
You need to create an account or log in to post comments to this site.