Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Array#pad! (See related posts)

My ri docco says there is an Array#pad! but runtime Ruby says there isn't. Bah. So I wrote one:

   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

Comments on this post

nicwilliams posts on Apr 07, 2008 at 06:48
Actually now I put it in a module and include it: http://pastie.caboo.se/176445
alxx posts on Apr 07, 2008 at 11:26
Here's something even lighter:

   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
alxx posts on Apr 07, 2008 at 11:35
Minor typo: with your naming convention, the first example would need (expected_length - length).times
ChronicStar posts on Apr 07, 2008 at 23:23
If you just want to pad with nil, how about this:

   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.


Click here to browse all 5545 code snippets

Related Posts