4

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)
Ronan Boiteau
  • 9,608
  • 6
  • 34
  • 56

2 Answers2

5

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
Ronan Boiteau
  • 9,608
  • 6
  • 34
  • 56
  • 1
    There's a toplevel convenience method: https://crystal-lang.org/api/0.25.1/toplevel.html#rand%28x%29-class-method – Jonne Haß Jul 27 '18 at 09:13
4

Even shorter is rand:

# ints
rand(10)
rand(10..20)

# floats
rand(1.5)
rand(6.2..18.289)
Johannes Müller
  • 5,581
  • 1
  • 11
  • 25