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)
Random
module
Integer
Random.new.rand(10) # >= 0 and < 10
Random.new.rand(10..20) # >= 10 and < 20
Float
Random.new.rand(1.5) # >= 0 and < 1.5
Random.new.rand(6.2..18.289) # >= 6.2 and < 18.289
rand
As pointed out by @Jonne in the comments, you can directly use the top-level method rand
that calls the Random
module:
Integer
rand(10) # >= 0 and < 10
rand(10..20) # >= 10 and < 20
Float
rand(1.5) # >= 0 and < 1.5
rand(6.2..18.289) # >= 6.2 and < 18.289
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With