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.
With random numbers, it is important to carefully consider the range of the rand function. In Ruby the maximum is inclusive (included).
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.
# 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 = rand 0..5 puts r end0.3299959902490742 2 4 2 0 1 5
This seeds the random number generator. Typically it is best not to invoke this method. It may make the random number stream more deterministic.
# Use constant seed. srand 1 # Display random numbers. puts rand puts rand0.417022004702574 0.7203244934421581
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).
string
has 26 chars. Index
0 is "a" and index 25 is "z." Other values could be added.def random_lowercase() # Lookup table of lowercase letters. letters = "abcdefghijklmnopqrstuvwxyz" # Get random index within range. # ... Return letter at that position. r = rand 0..25 return letters[r] end # Invoke our random_lowercase method. 10.times do puts random_lowercase() endl a q i v s i b d q
Random
stringsThis method builds on our "random lowercase letter" method. We generate a string
of a certain length. We place a random letter "length" times.
def random_string(length) # All lowercase letters. letters = "abcdefghijklmnopqrstuvwxyz" # Empty Array for letters we add. word = Array[] # Add all random letters. length.times do # Get random index within string. r = rand 0..25 # Get letter for index. letter = letters[r] # Push to our array. word.push(letter) end # Return random string joined together. result = word.join("") result.upcase() end # Call our random_string method many times. 3.upto(10) do |i| puts random_string(i) puts random_string(i) endPXR ABG IMCH KCXF IPABT PCRVD WLOGIT PHYMKJ FMSGOBD VPDZLRC SECFHGLE UMTYPZTH XSVREENYR EUUVXQKLN SJJURAVBXS JXSIPXSVTI
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.