Random Numbers and Strings in Ruby
Randomness can make things more interesting in games or it can help make your sites Clinica Stomatologie Bucuresti curs valutar crama lechinta Psiholog Cluj more secure. In Ruby, there are multiple ways to generate random numbers with various properties. Let’s start by generating some Ruby random numbers using the rand method.

Rand produces decimal numbers if called without any arguments, but most of the time you will want whole numbers. You can pass an argument to rand to tell it to generate a number starting from zero up to (but not including) our number.
rand 100
> 41
As you can see, Ruby random number generation is really easy, but what if you need the number to be in a specific range instead of starting from zero? Not a problem, you can just use a range to get exactly what you need.
Example:
rand 200..500
> 352
Better Ruby Random Numbers
The numbers produced by rand might be enough for a simple application, but if you want to use them for security purposes —like generating a password reset token— then you should use SecureRandom, which is part of the Ruby standard library.
SecureRandom seeds its generator from /dev/urandom on Unix systems and on windows it uses the CryptAcquireContext / CryptGenRandom API.
require 'securerandom'
SecureRandom.random_number
> 0.232
As you can see this works a lot like rand, you can also pass in a max number.
SecureRandom.random_number 100
> 72
In addition, SecureRandom has other output formats available. Using .hex it can generate a hexadecimal fixed-width string.
SecureRandom.hex
> "87694e9e5231abca6de39c58cdfbe307"
Docs: http://ruby-doc.org/stdlib-2.1.2/libdoc/securerandom/rdoc/SecureRandom.html
Sampling
Next, we may want to do a random pick from a list. You might be tempted to do this:
[5, 15, 30, 60].shuffle.first
> 30
But Ruby has the sample method which is better suited (and faster) for this task:
[5, 15, 30, 60].sample
> 5
We can also use sample for ranges, this code generates a random letter:
('a'..'z').to_a.sample
> b
Ruby Random Strings
The ultimate randomness application is to generate a random string with a custom character set. Here is the code:
def generate_code(number)
charset = Array('A'..'Z') + Array('a'..'z')
Array.new(number) { charset.sample }.join
end
puts generate_code(20)
There are a few things going on here.
First, we prepare our charset using ranges and converting them to arrays. Then we take advantage of calling Array.new with a block, which lets us initialize an array of size n with the values produced by the block.
This code will produce strings of the following form: TufwGfXZskHlPcYrLNKg. You can tweak the character set to fit your needs.
Conclusion
That’s it! You are now ready to start using randomness in your Ruby programs 🙂
Found this post useful? Share it with your friends & subscribe to my newsletter so you don’t miss anything new!