C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
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 = rand 0..5
puts r
end
Output
0.3299959902490742
2
4
2
0
1
5
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.
srand 1
# Display random numbers.
puts rand
puts rand
Output
0.417022004702574
0.7203244934421581
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
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()
end
Output
l
a
q
i
v
s
i
b
d
q
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
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("")
end
# Call our random_string method many times.
3.upto(10) do |i|
puts random_string(i)
puts random_string(i)
end
Output
oko
pig
heav
yafh
yvcuu
wgbep
uaosje
uywvyc
pttwiau
wqcxpyq
zzudlihd
kckqhqfd
tffatuubx
oulqkdfyw
civpxnsdjb
yrvvqbdwsv