Ad space (banner)
๐Ÿ’ŽRuby Lessons
Lesson 53 / 68

Generating Random Numbers

In this lesson you will learn to generate random values with rand and Array#sample so you can build things like dice and raffles. This is for anyone searching for "Ruby random number generation".

rand() and Array#sample give you a random number, or a randomly chosen value from an array. Use them for dice rolls and raffles. The result changes every time you run it.

The sample code rolls a die from 1 to 6 with rand(1..6) and picks one of Rock, Scissors, and Paper with choices.sample. Notice how intuitively you can pass a range (1..6) straight to rand().

A common stumbling block for beginners is the difference between rand(6) and rand(1..6). Without a range, rand(6) returns 0 to 5, so the range form is the accurate way to get a die roll from 1 to 6.

The standard library also provides SecureRandom for randomness that is harder to predict. Random values are used widely, from shuffling in a game to sampling in a simulation.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Ruby directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)