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)


Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
You'll get a notification every time a post gets published here.

Related posts

How to install and uninstall gem in Ruby Programming| Ruby on Rails by Example

How to do sum of array numbers in Ruby with examples

How to check the type of a variable is Ruby| Ruby on Rails By Example

How to convert Class or Hash Object to JSON Object Ruby| Ruby on Rails By Example

How to remove duplicate elements from an array in Ruby with examples

How to Convert current Unix timestamp epoch to DateTime in Ruby Programming| Ruby on Rails by Example

How to remove an element from an array in Ruby Programming| Ruby on Rails by Example