Home » Ruby programming » Ruby programs

Ruby program to generate random numbers

Generating random numbers: Here, we are going to learn how to generate random numbers in Ruby programming language?
Submitted by Hrithik Chandra Prasad, on August 10, 2019

Generating random number

The task is to generate and print random number.

Generating random numbers means that any number can be provided to you which is not dependent on any pre-specified condition. It can be anything but must be within a range or limit. Ruby provides you the method for meeting the purpose.

Methods used:

  • puts: This method is used to put strings as messages on the screen for creating a better interaction with the user.
  • gets: This method is used to take input from the user.
  • rand: This method is a pre-defined method in Ruby library which Is specifically defined for generating a random number. It can be invoked with parameters only otherwise it will give decimal results which are most of the times less than 0. The examples are:
        rand(6)
        rand(0..6)
        rand(9..24)

Variables used:

  • up: It is used to store the upper limit.
  • lm: It is used to store the lower limit.

Ruby code to generate random numbers

=begin 
Ruby program to pick a random number from a range
=end

#input upper and lower limits
puts "Enter upper limit"
up=gets.chomp.to_i
puts "Enter lower limit"
lm=gets.chomp.to_i

#generate and print the random numbers
#between the given lower and upper limit
puts "The random numbers are..."
puts rand(lm..up)
puts rand(lm..up)
puts rand(lm..up)
puts rand(lm..up)
puts rand(lm..up)

Output

Enter upper limit
100
Enter lower limit
50
The random numbers are...
91
98
96
95
84

Additional program:

The same concept can be applied to create a lucky draw program in which user will enter his/her name and they will get to know what they have won based on the random number generated by the program.

=begin 
Ruby program for Lucky draw.
=end

puts "Lucky Draw"
#input the name
puts "Enter your name"
name=gets.chomp

#generate a random number 
#pick a lucky number
chk=rand(8) #For getting a random value

#print the result based on the random
#generated lucky number
case chk
when 0
	puts "#{name} got Maruti 800"
when 3
	puts "#{name} won iphone X"
when 8
	puts "#{name} won Rs 10"
when 6
	puts "#{name} won Samsung A50"
else
	puts "#{name}, Better luck next time"
end

Output

RUN 1 : 
Lucky Draw
Enter your name
Sunaina
Sunaina, Better luck next time

RUN 2: 
Lucky Draw
Enter your name
Hargun
Hargun, Better luck next time

RUN 3 :
Lucky Draw
Enter your name
Kajal
Kajal won iphone X

RUN 4: 
Lucky Draw
Enter your name
Shivang
Shivang got Maruti 800


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.