Generate random numbers

1

I have the following problem:

  • I need to generate a random number between 1 and 6
  • Assign a array of numbers if this new one is not contained in array
  • If contained, regenerate. Do this process until the array of numbers has 6 numbers
asked by anonymous 12.01.2016 / 12:14

2 answers

6

You are already thinking about how to implement procedural. I understand you want an array with the numbers 1 to 6 in random order. To do this, use the Array # shuffle method.

(1..6).to_a.shuffle
=> [6, 3, 5, 4, 1, 2]
    
12.01.2016 / 19:39
1

To generate random numbers use the rand method, it generates a decimal number from 0.0 to 1.0 if used without arguments.

To use with integers pass an integer parameter like this:

rand NUM_INT

This will generate a number from 0 to NUM_INT - 1.

You can also generate random numbers in a given range!

For example, to have numbers between 50 and 100:

rand 50..101
    
12.01.2016 / 15:31