Ruby Language

Generate a random number

Introduction#

How to generate a random number in Ruby.

Remarks#

Alias of Random::DEFAULT.rand. This uses a pseudo-random number generator which approximates true randomness

6 Sided die

   # Roll a 6 sided die, rand(6) returns a number from 0 to 5 inclusive
   dice_roll_result = 1 + rand(6)

Generate a random number from a range (inclusive)

# ruby 1.92
lower_limit = 1
upper_limit = 6
Random.new.rand(lower_limit..upper_limit) # Change your range operator to suit your needs

This modified text is an extract of the original Stack Overflow Documentation created by the contributors and released under CC BY-SA 3.0 This website is not affiliated with Stack Overflow