Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate a random number in Crystal?

In Crystal, how can I generate a random number?


Using Python, I can simply do the following to generate a random integer between 0 and 10:

from random import randint
nb = randint(0, 10)
like image 383
Ronan Boiteau Avatar asked Jan 03 '23 02:01

Ronan Boiteau


1 Answers

Solution 1 - Use the Random module

Random Integer

Random.new.rand(10)      # >= 0 and < 10
Random.new.rand(10..20)  # >= 10 and < 20

Random Float

Random.new.rand(1.5)          # >= 0 and < 1.5
Random.new.rand(6.2..18.289)  # >= 6.2 and < 18.289

Solution 2 - Use the top-level method rand

As pointed out by @Jonne in the comments, you can directly use the top-level method rand that calls the Random module:

Random Integer

rand(10)      # >= 0 and < 10
rand(10..20)  # >= 10 and < 20

Random Float

rand(1.5)          # >= 0 and < 1.5
rand(6.2..18.289)  # >= 6.2 and < 18.289
like image 93
Ronan Boiteau Avatar answered Feb 15 '23 13:02

Ronan Boiteau