For my web app that I am currently building, I needed a way to generate a random item number for each new item that was posted to the site. Since I am building this app in Rails, I felt pretty sure that Ruby had a great and easy to generate a random number, and I was right.

Now, keep in mind that what I have done here does not truly generate a “random” number, as the number could in fact be generated again. However, for what I needed to do, this works just fine.

First, in my Item model I placed a simple before_create statement in:

before_create :generate_item_number

I then define that below a protected statement in order to actually generate the random number:

def generate_item_number
self.item_number= rand(9999999).to_s.center(7, rand(9).to_s)
end

This little snippet of code generates a random 7-digit number that is written to the database in the item_number column of my Item table.

If you wanted to change that to be a 10-digit number, just change the (9999999) to be 10 9’s and change the 7 that I have there to 10. Probably not the best way to go about doing this, but in my very limited Ruby/Rails knowledge, it works for me.

Share and Enjoy:
  • Digg
  • Technorati
  • del.icio.us
  • StumbleUpon
  • NewsVine


  • RELATED / YOU MIGHT FIND THESE INTERESTING
  • No related posts




COMMENTS / ONE COMMENT

Why not simply use:
“%09d” % rand(1000000000)

There may even be a simpler way than that though… perhaps:

Array.new(9){rand 10}.join

Dimo added these pithy words on Oct 17 08 at 1:50 pm


SPEAK / ADD YOUR COMMENT
Comments are moderated.

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Return to Top