<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet href="/stylesheets/rss.css" type="text/css"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/">
  <channel>
    <title>random utterings...: Tag faker</title>
    <link>http://blog.randomutterings.com/articles/tag/faker</link>
    <language>en-us</language>
    <ttl>40</ttl>
    <description></description>
    <item>
      <title>Fixed Length Random numbers in Ruby</title>
      <description>&lt;p&gt;My latest project is almost complete and we're setting up a demo site with lots of fake data already included so I used the faker gem to generate most of it.&lt;/p&gt;

&lt;p&gt;One issue I had that I couldn't do with the faker gem out of the box is get a fixed length random number.  I need this for license numbers, credit card numbers, phone numbers and others.  The faker gem does offer a random phone number but the ones in my project don't support extensions or punctuation so rather than generating the number then using string functions to strip out the stuff I didn't want, I decided to find an easier way.&lt;/p&gt;

&lt;p&gt;I started by Googling for it assuming that someone else had already figured it out and while I'm sure its been done a hundred times before, I couldn't find it anywhere.  So after much thought and digging through the ruby docs, this is what I came up with.&lt;/p&gt;

&lt;blockquote&gt;
&lt;code&gt;
rand(9999999999).to_s.center(10, rand(9).to_s)
&lt;/code&gt;
&lt;/blockquote&gt;

&lt;p&gt;rand(9999999999) will give me a number between 0 and 9999999999.  Convert it to a string and use the center method to make sure its at least 10 digits long and pad the rest with a random number from 0-9.  rand(9)&lt;/p&gt;

&lt;p&gt;If you need a number of say 7 digits in length, just change the first rand to rand(9999999) and change the center method length to 7 so it looks like this.&lt;/p&gt;

&lt;blockquote&gt;
&lt;code&gt;
rand(9999999).to_s.center(7, rand(9).to_s)
&lt;/code&gt;
&lt;/blockquote&gt;

&lt;p&gt;Hope this is helpful to someone.&lt;/p&gt;




</description>
      <pubDate>Wed, 09 Jan 2008 11:20:00 -0500</pubDate>
      <guid isPermaLink="false">urn:uuid:3d11eeca-de64-42c7-86ea-9f74999c2057</guid>
      <author>Chris Barnes</author>
      <link>http://blog.randomutterings.com/articles/2008/01/09/fixed-length-random-numbers-in-ruby</link>
      <category>Ruby</category>
      <category>ruby</category>
      <category>random</category>
      <category>numbers</category>
      <category>faker</category>
      <category>gem</category>
      <trackback:ping>http://blog.randomutterings.com/articles/trackback/26</trackback:ping>
    </item>
  </channel>
</rss>
