How to Generate Random Numbers - Ruby Programming Beginner Tutorial
As with many things in Ruby, generating a random number is quite straight forward. The rand
function gives you a random (enough) floating-point number between 0 and 1 (up to but not including 1). You can pass a parameter to specify the settings for your random number.
You can try any of this code online at https://repl.it.
Ways to Call rand
rand
The rand
function with no parameters returns a floating-point number from 0 up to 1 (but not including 1).
rand(x)
rand(x)
will give you an integer (whole number) from 0 up to x (but not including x). So rand(6)
will give you integers in the range of 0 and 5.
rand(3)
can return either 0, 1, or 2.
rand(1)
will only give you 0.
rand(0)
just gives you a floating-point between 0 and 1, the same as using no parameters, because 0 is not a range.
Following is a bunch of random integers, done many times over.
Seeing as how everything starts at 0, if you'd like to get random six-sided dice roll, you'd need to get random numbers in the range of 1 to 6 (inclusive). One way to do that is to get a random number between 0 and 5 and add 1!
rand(6) + 1
(A Dice Roll)
rand(x..y)
Ruby allows us to use a range as a parameter to the random function.
rand(x..y)
(inclusive of y
) and rand(x...y)
(not inclusive of y
)
rand(0.8...1.2)
Finally, you can get random floating-point numbers in a range if you specify floating point numbers as the range parameters.
These are the ways of getting basic random numbers (non-seeded) in Ruby. Thanks for reading.
Congratulations @inplainenglish! You have completed some achievement on Steemit and have been rewarded with new badge(s) :
Click on any badge to view your own Board of Honor on SteemitBoard.
For more information about SteemitBoard, click here
If you no longer want to receive notifications, reply to this comment with the word
STOP
Congratulations @inplainenglish! You received a personal award!
Click here to view your Board
Congratulations @inplainenglish! You received a personal award!
You can view your badges on your Steem Board and compare to others on the Steem Ranking
Vote for @Steemitboard as a witness to get one more award and increased upvotes!