1
I have the following problem:
- I need to generate a random number between 1 and 6
- Assign to a array of numbers if this new number is not contained in array
- If contained, generate again. Do this process until the array number have 6 numbers
1
I have the following problem:
6
You are already thinking about how to implement in procedural form. From what I understand you want an array with the numbers 1 to 6 in random order. For this use the method Array#shuffle.
(1..6).to_a.shuffle
=> [6, 3, 5, 4, 1, 2]
That’s just what I need, thank you !
1
To generate random numbers use the method rand
, it generates a decimal number from 0.0 to 1.0 if used without arguments.
To use with integers pass an integer parameter this way:
rand NUM_INT
This will generate a number from 0 up to NUM_INT - 1.
You can also generate random numbers in a certain range!
For example, to have numbers between 50 and 100:
rand 50..101
Browser other questions tagged array ruby-on-rails ruby random
You are not signed in. Login or sign up in order to post.
don’t understand the last case, don’t you want them to repeat themselves if they run again? @Danilotiagothaisantos
– Wellington Avelino
In this case, it is just an array of numbers that do not repeat, I will use the function (1.6). to_a.shuffle
– Danilo Tiago Thai Santos
Great, then Guigs' answer meets you :), mark as sure later if it helped you
– Wellington Avelino
Has any answer served you, if yes accept it as a solution to your problem ???
– novic