How to Generate Random number in Ruby with examples

This article explains about multiple examples how to generate random number.

How to Generate Random Number in Ruby?

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

How to generate Random String in Ruby?

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

  • hex
  • random_bytes
  • base64
  • random_number
  • urlsafe_base64

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