Search code examples
randomcrystal-lang

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)

Solution

  • 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