Chance and dice
Games need surprises, and programs sometimes need chance: a die roll, a random card, a password. Ruby's die is called rand. With a number it rolls from 0 up to below it, with a range exactly within that range – and with nothing at all, a decimal between 0 and 1. Run the cell a few times:
p rand(6) # 0 to 5
p rand(1..6) # 1 to 6 - like a die
rand # a decimal between 0 and 1Arrays can roll dice, too: sample draws one random element (or several), shuffle mixes the whole list – like a deck of cards. The original stays as it is:
snacks = ["bacon", "egg", "toast", "cheese"]
p snacks.sample
p snacks.sample(2)
snacks.shuffleYou collect many throws at once in an array with times.map – every pass of the block is one throw. Then you can evaluate them, for instance count how often the six came up with count:
throws = 20.times.map { rand(1..6) }
p throws
throws.count(6)A secret: computers do not really roll dice. From a starting value they compute a sequence that merely looks random. With srand you set that starting value yourself – and get the same numbers every time. That is worth gold when you are hunting a bug or testing a game:
srand(42)
first = 5.times.map { rand(1..6) }
srand(42)
second = 5.times.map { rand(1..6) }
first == secondWith if from lesson 5 (decisions) this becomes a game. Who rolls higher, Chunky or you? Run the cell until you win:
chunky = rand(1..6)
you = rand(1..6)
puts "Chunky rolls #{chunky}, you roll #{you}."
if chunky > you
"Chunky wins!"
elsif you > chunky
"You win!"
else
"A draw - roll again!"
endChance is unpredictable – but only in the small. Roll a thousand times and the average almost always lands near 3.5, the middle between 1 and 6. Try it: every run gives a different number, but they all sit close together.
throws = 1000.times.map { rand(1..6) }
throws.sum / 1000.0That already lets you build a lot: a memory game with shuffled cards, a random name generator, a coin (["heads", "tails"].sample). Chunky's Snake in lesson 87 puts the bacon on a free cell with sample, and lesson 76 (statistics) works out how likely five sixes in twenty throws are.
rand(1..6) – and store the 100 totals in the array totals. Then count in sevens how often 7 came up (the most common total!).# 100 throws with two dice: every total in totals
# totals = 100.times.map { ... }
# sevens = ...
numbers are three different numbers from 1 to 10, sorted – sample with a count draws without putting back, and (1..10).to_a turns the range into an array. Then coins: ten coin flips, each "heads" or "tails".# numbers = ... # 3 different numbers from 1 to 10, sorted
# coins = ... # 10 coin flips: "heads" or "tails" each