THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.
This article explains about multiple examples how to generate random number.
rand
method in used to generate the random number.
rand() without argument always returns the random number between 0.0 and 1.0. rand() - returns .5 value
puts rand() # return random number between 0.0 to 1.0
Here is an example
It takes individual number or start and ending index to generate number.
puts rand(10) # return random number between 0 to 9
puts rand(1 .. 20) # return random number between 1 to 20
Random String is unique characters groups that does not repeat for every execution.
SecureRandom
class contains methods for generation of strings.
It contains below methods
Here is an code examples
require 'securerandom'
# Generate random hexa string
puts SecureRandom.hex
# Generate random string in base64 string with given length
puts SecureRandom.base64(4)
puts SecureRandom.base64(16)
# Generate random bytes
puts SecureRandom.random_bytes
# Generate random floating number between 0 and 1
puts SecureRandom.random_number
# Generate random urlsafe base64 string
puts SecureRandom.urlsafe_base64(4)
# Generate random alphanumeric string
puts SecureRandom.alphanumeric(20)
Output:
b5b4c1744374fba5c699d4f4033698a5
E+I/ig==
ShofUxlYH6AjRna0HSs/RQ==
����x$�t
�ğ�
0.5543919005899334
5BeL0Q
i6BjtXocvGFJHr48zGV7
🧮 Tags
Recent posts
Julia examples - Variable Type Nim example - Convert String to/from the Int How to get length of an array and sequence in Nim? Nim environment variables - read, set, delete, exists, and iterate examples? How to convert from single character to/from string in Nim?Related posts