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"
