Rand. With rand() in Ruby, we can provide a range of numbers, and get a random number in return. We can then access a random letter or an array element.
Range info. With random numbers, it is important to carefully consider the range of the rand function. In Ruby the maximum is inclusive (included).
Range example. Here we use rand with a range. The range is inclusive—the lowest or highest bounding numbers may be returned by rand. By default, a range of 0 to 1 is used.
Here We generate a random number between 0 and 1. Then we generate six more, all between 0 and 5 (inclusively).
Srand The srand method is also available: this seeds the random number generator. Srand is not normally needed.
Note Calling srand with a constant number will make a program always use the same random numbers.
Ruby program that uses random numbers
# Display random number between 0 and 1.
puts rand# Display 6 random numbers between 0 and 5 inclusive.
for i in 0..5# Call with range.
r = rand0..5
Srand. This seeds the random number generator. Typically it is best not to invoke this method. It may make the random number stream more deterministic.
Note If you use a constant with srand, the random stream of numbers is not random anymore. This does not seem random.
Instead Each time I run this program, it returns 0.41 and 0.72. This is because the random number generator was seeded with a constant 1.
Ruby program that uses srand
# Use constant seed.srand1# Display random numbers.
Lowercase letters. There are 26 lowercase ASCII letters in the English alphabet. With rand we can generate random lowercase letters with an index from 0 to 25 (inclusive).
Note The "letters" string has 26 chars. Index 0 is "a" and index 25 is "z." Other values could be added.
Ruby program that generates random lowercase letters
# Lookup table of lowercase letters.
letters = "abcdefghijklmnopqrstuvwxyz"# Get random index within range.# ... Return letter at that position.
r = rand0..25
# Invoke our random_lowercase method.
Random strings. This method builds on our "random lowercase letter" method. We generate a string of a certain length. We place a random letter "length" times.
Array We start with an empty array (we call this array the "word" array). We add letters to this array.
Times We use the times iterator to add the required number of letters to our word array. We access letters using a range-based rand call.
Ruby program that generates random strings
# All lowercase letters.
letters = "abcdefghijklmnopqrstuvwxyz"# Empty Array for letters we add.
word = Array
# Add all random letters.
# Get random index within string.
r = rand0..25# Get letter for index.
letter = letters[r]
# Push to our array.
# Return random string joined together.
result = word.join("")
# Call our random_string method many times.
3.upto(10) do |i|
A review. With Ruby we get a powerful and easy-to-use pseudo-random number generator. We call rand() with an optional (and usually necessary) range argument.