Skip to content

vikingtechblog

Recent Posts

  • Setting Up Paperclip
  • Accessing AR-Drone 2.0 Video Feed
  • How to Use Exercism.io
  • Making a Ruby Gem Beginners Guide
  • ServiceWeb Preview

Recent Comments

Archives

  • May 2016
  • April 2016
  • March 2016
  • January 2016
  • December 2015
  • November 2015

Categories

  • Uncategorized

Meta

  • Create account
  • Log in
  • Entries feed
  • Comments feed
  • WordPress.com

account numbers

Ruby: A few ways to make fixed-length random numbers

November 4, 2015November 4, 2015 gatorjuiceaccount numbers, fixed, random, rubyLeave a comment

With all the simplicity built into ruby, it’s kind of weird to me that creating a fixed length random number string isn’t as easy as I originally may have though.

You probably know that creating a random integer can be quite easy and under certain circumstances the rand() method by itself will suffice. Take this example:

random_number = rand(111111..999999).to_s
=> "899448"

This obviously creates a random number and that’s fine, but what if you need to account for leading zeros? That’s where Ruby start to leave the rails, pardon the expression. For this, there are many very good options but I want to show a few of my favorite.

Lets look at a very simple option: <— joke

random_10_digit = rand(9999999999).to_s.center(10, rand(9).to_s)
=> "4074265759"

Aaaaand lets do probably the best option I’ve seen:

random_10_digit = Array.new(10){rand(0..9)}.join
=> "4214519794"
Ruby: A few ways to make fixed-length random numbers
Create a free website or blog at WordPress.com.
Privacy & Cookies: This site uses cookies. By continuing to use this website, you agree to their use.
To find out more, including how to control cookies, see here: Cookie Policy
  • Subscribe Subscribed
    • vikingtechblog
    • Already have a WordPress.com account? Log in now.
    • vikingtechblog
    • Subscribe Subscribed
    • Sign up
    • Log in
    • Report this content
    • View site in Reader
    • Manage subscriptions
    • Collapse this bar